I've got a script which works fine which lists all files modified since last 7 days and want to modify it to add file owner to the export csv file.
$dir_to_look="F:\"
$month_backdate=$(Get-Date).AddDays(-7)
Get-Childitem $dir_to_look -Recurse | ? { !($_.psiscontainer) -and $_.LastWriteTime -gt $month_backdate } | ForEach-Object {Get-Acl $_.FullName}.owner | Select-object LastWriteTime, Directory, FullName | export-csv -path \\sharename\report.csv -encoding "unicode"
But not sure how to correctly add get-acl to the pipe as currently it prints nothing to my report file
Your Foreach-Object command should be:
... | Foreach-Object {Add-Member -Input $_ -Type NoteProperty -Name Owner -Value (Get-Acl $_.Fullname).Owner -PassThru} | Select-object LastWriteTime, Directory, FullName, Owner | ...
Add-Member is handy for adding properties (and methods) to objects.
Use a hash table with Select-Object.
$dir_to_look="F:\"
$month_backdate=$(Get-Date).AddDays(-7)
Get-Childitem $dir_to_look -Recurse | ? { !($_.psiscontainer) -and $_.LastWriteTime -gt $month_backdate } |
Select-object LastWriteTime, Directory, FullName, #{n='Owner';e={(Get-ACL $_.FullName).owner}}
$dir_to_look="F:\"
$month_backdate=$(Get-Date).AddDays(-7)
Get-Childitem $dir_to_look -Recurse | ? { !($_.psiscontainer) -and $_.LastWriteTime -gt $month_backdate } |
Select-object LastWriteTime, Directory, FullName, #{n='Owner';e={(Get-ACL $_.FullName).owner}}
Related
Export Name and the status of the first 10 services into a html file and color the lines with Running green and Stopped red.
This was the task.
I tried to:
Get-Service | Select-Object -First 10 -Property Name,Status
Get-Service | Select-Object -First 10 -Property Name,Status | ConvertTo-Html > first.txt
(Get-Content hallo.txt) -replace '<td>','<td style="color:#00ff00">'|Set-Content final.html
But now I have the problem that everything is green.
How do I manage to distinguish between Stopped and Running?
I think this idea I've been trying to come up with isn't working.
Maybe you could make the distinction before you export the processes to the file? But I have no idea how to do that.
If we are sticking with the theme of text replacement, you could do the following:
$html = Get-Service | Select-Object -First 10 -property Name,Status |
ConvertTo-Html | Foreach-Object {
if ($_ -match '<td>Stopped</td>') {
$_ -replace '<td>','<td style="color:red">'
}
elseif ($_ -match '<td>Running</td>') {
$_ -replace '<td>','<td style="color:green">'
}
else {
$_
}
}
$html | Set-Content final.html
You can also do this:
Get-Service | Select -First 10 -Property Name,Status | ConvertTo-Html | Foreach {
Switch -regex ($_) {
".*<td>Stopped</td>.*" { $_ -replace '<td>','<td style="color:red">' }
".*<td>Running</td>.*" { $_ -replace '<td>','<td style="color:green">'
}
} | Set-Content "Filepath"
Hello I Used below code to Merge CSV files using one common Key for adding one column from Child.CSV to Parent.CSV.
{
Import-Csv "D:\CSV check\Sourcecount.csv" -Header Sourcecount, MONTH_YEAR | ForEach-Object -Begin {
$Employees = #{}
} -Process {
$Employees.Add($_.MONTH_YEAR,$_.Sourcecount)
}
Import-Csv "D:\CSV check\RenameFinal.csv" | ForEach-Object {
$_ | Add-Member -MemberType NoteProperty -Name Sourcecount -Value $Employees."$($_.MONTH_YEAR)" -PassThru
} | Export-Csv -NoTypeInformation "D:\CSV check\sourcefinal.csv"
}
Question:
Can you please help for the scenario joining for getting one column value from child.csv to Parent.csv for two common keys (by data and by userid).
Below is the code I used to solve the above Query:
$f2=Import-Csv "D:\Sourcecount.csv" -Header Sourcecount,MONTH_YEAR,UserID
$f1= Import-csv "D:\Final.csv" -Header MONTH_YEAR,DestinationCount,UserID,Result,SourceCount
$f1|
%{
$Month_YEAR=$_.MONTH_YEAR
$UserID=$_.UserID
$m=$f2|?{$_.MONTH_YEAR -eq $Month_YEAR}|?{$_.UserID -eq $UserID}
$_.SourceCount=$m.Sourcecount
}
$f1| Export-Csv "D:\SourceFinal.csv" -NoTypeInformation
I have list of machine in text file and I am trying to get the details of physical drives, OS architecture and physical memory. With the help of Matt (SO user) here is the powershell script.
$server = Get-Content .\Server.txt
#$infoObject11 = #{}
$infoObject11 = #{}
foreach ($server in $servers) {
# Gather all wmi drives query at once
$alldisksInfo = Get-WmiObject -Query "SELECT * FROM Win32_DiskDrive" -ComputerName $server -ErrorAction SilentlyContinue | Group-Object __Server
# Figure out the maximum number of disks
$MaximumDrives = $alldisksInfo | Measure-Object -Property Count -Maximum | Select-Object -ExpandProperty Maximum
# Build the objects, making empty properties for the drives that dont exist for each server where need be.
$server | ForEach-Object {
# Clean the hashtable
$infoObject1 = #{}
# Populate Server
$infoObject1.Server = $server
$HOSTNAME = Get-WMIObject -Query "Select * from Win32_OperatingSystem" -ComputerName $infoObject1.Server
# Add other simple properties here
$infoObject1.PhysicalMemory = (Get-WmiObject Win32_PhysicalMemory -ComputerName $infoObject1.Server | Measure-Object Capacity -Sum).Sum/1gb
$infoObject1.OSarchitecture =$HOSTNAME.osarchitecture
# Add the disks information from the $diskInfo Array
$serverDisksWMI = $alldisksInfo | Where-Object{$_.Name -eq $infoObject1.Server} | Select-Object -ExpandProperty Group
for ($diskIndex =0; $diskIndex -lt $MaximumDrives;$diskIndex++) {
$infoObject1."PhysicalDisk$diskIndex" = [Math]::Round(($serverDisksWMI | Where-Object{($_.DeviceID -replace "^\D*") -eq $diskIndex} | Select -Expand Size)/1GB)
}
}
# Create the custom object now.
New-Object -TypeName psobject -Property $infoObject1 | Export-Csv -path .\Server_Inventory_$((Get-Date).ToString('MM-dd-yyyy')).csv -NoTypeInformation
}
Problem is in the CSV file I am getting single machine details but in server.txt file there are more than 1 machine. If I print $infoObject1 before New-Object then I can see there are details of multiple machine. It seems like some issue with array and I am not able to export it in CSV.
Can anybody please suggest on this.
It looks like you are having issues integrating my code. You have added a second loop that should not be there. Also as other users pointed out you are not creating the per server object outside the loop. The answer, from where your code comes from, has that part correct. I had even showed you where to put the Export-CSV.
$servers = Get-Content .\Server.txt
# Gather all wmi drives query at once
$alldisksInfo = Get-WmiObject -Query "SELECT * FROM Win32_DiskDrive" -ComputerName $servers -ErrorAction SilentlyContinue | Group-Object __Server
# Figure out the maximum number of disks
$MaximumDrives = $alldisksInfo | Measure-Object -Property Count -Maximum | Select-Object -ExpandProperty Maximum
# Build the objects, making empty properties for the drives that dont exist for each server where need be.
$servers | ForEach-Object {
# Clean the hashtable
$infoObject1 = #{}
# Populate Server
$infoObject1.Server = $_
# Add other simple properties here
$infoObject1.PhysicalMemory = (Get-WmiObject Win32_PhysicalMemory -ComputerName $infoObject1.Server | Measure-Object Capacity -Sum | Select-Object -ExpandProperty Sum)/1GB
$infoObject1.OSarchitecture = Get-WMIObject -Query "Select * from Win32_OperatingSystem" -ComputerName $infoObject1.Server | Select-Object -ExpandProperty OSArchitecture
# Add the disks information from the $diskInfo Array
$serverDisksWMI = $alldisksInfo | Where-Object{$_.Name -eq $infoObject1.Server} | Select-Object -ExpandProperty Group
for ($diskIndex =0; $diskIndex -lt $MaximumDrives;$diskIndex++) {
$infoObject1."PhysicalDisk$diskIndex" = [Math]::Round(($serverDisksWMI | Where-Object{($_.DeviceID -replace "^\D*") -eq $diskIndex} | Select-Object -ExpandProperty Size)/1GB)
}
# Create the custom object now for this pass in the loop.
New-Object -TypeName psobject -Property $infoObject1
} | Export-Csv -path .\Server_Inventory_$((Get-Date).ToString('MM-dd-yyyy')).csv -NoTypeInformation
foreach ($server in $servers) {
...
New-Object -TypeName PSObject -Property $infoObject1 |
Export-Csv -Path .\Server_Inventory_$((Get-Date).ToString('MM-dd-yyyy')).csv -NoTypeInformation
}
You're exporting inside the loop without using the parameter -Append (available in PowerShell v3 and newer). That overwrites your output file with each iteration, leaving you with just the data of the last server.
Either use the parameter -Append (if you have PowerShell v3 or newer):
foreach ($server in $servers) {
...
New-Object -TypeName PSObject -Property $infoObject1 |
Export-Csv -Append -Path .\Server_Inventory_$((Get-Date).ToString('MM-dd-yyyy')).csv -NoTypeInformation
}
or move Export-Csv outside the loop (works with all PowerShell versions):
(foreach ($server in $servers) {
...
New-Object -TypeName PSObject -Property $infoObject1
}) | Export-Csv -Path .\Server_Inventory_$((Get-Date).ToString('MM-dd-yyyy')).csv -NoTypeInformation
Note that you need to run the loop in parentheses for this to work, as foreach loops don't output to the pipeline.
You could also replace the foreach loop with ForEach-Object if you want to feed the pipeline directly:
Get-Content .\Server.txt | ForEach-Object {
$server = $_
...
New-Object -TypeName PSObject -Property $infoObject1
} | Export-Csv -Path .\Server_Inventory_$((Get-Date).ToString('MM-dd-yyyy')).csv -NoTypeInformation
I'm trying to gather certificate extensions into a csv. The PowerShell commands seem to display just fine within PowerShell but when piped to a csv they display other types of data?
$cert = Get-ChildItem cert:\localmachine -Recurse
($cert.Extensions | Where-Object {$_.Oid.FriendlyName -eq "Key Usage"}).Format(1) | Export-Csv C:\Folder\File.csv
After searching the web I tried something different but still was unable to get the data to get captured and displayed as it does within PowerShell.
$cert=Get-ChildItem cert:\localmachine -Recurse
$sanExt=$cert.Extensions | Where-Object {$_.Oid.FriendlyName -match "subject alternative name"}
$sanObjs = new-object -ComObject X509Enrollment.CX509ExtensionAlternativeNames
$altNamesStr=[System.Convert]::ToBase64String($sanExt.RawData)
$sanObjs.InitializeDecode(1, $altNamesStr)
Foreach ($SAN in $sanObjs.AlternativeNames) {$SAN.strValue}
$sanExt.Format(1) | Export-Csv C:\Folder\File.csv
For others looking to also gather the extension fields, this was my resolution:
$cert = Get-ChildItem cert:\localmachine -Recurse
($cert.Extensions | Where-Object {$_.Oid.FriendlyName -eq "Key Usage"}).Format(1) |
Select-Object -Property #{Name="Certificate";Expression={$_}} |
Export-csv -Path C:\Folder\file.csv`
I'm using the code below to generate Index.htm page. The code works great, but the only thing that I don't want inside that Index.htm page is to have the hyperlinks for directories, as they are useless. Index.htm should contain only hyperlinks to the .htm files inside the C:\inetpub\wwwroot. Any suggestions on how to achieve such result?
$basedir = 'C:\inetpub\wwwroot'
$exp = [regex]::Escape($basedir)
$server = 'http://172.16.x.x'
Get-ChildItem $basedir -Force |
select Name, LastWriteTime,
#{n="URL";e={$_.FullName -replace $exp, $server -replace '\\', '/'}} |
ConvertTo-Html -Fragment URL, Name, LastWriteTime `
-PreContent '<html><head><title>Test</title></head><body>' `
-PostContent '</body></html>' |
% { $_ -replace '<th>.*</th>','<th>Files</th>' `
-replace '<td>(.*?)</td><td>(.*?)</td><td>(.*?)</td>',
'<td>$2 $3</td>'
} | Set-Content "c:\inetpub\wwwroot\index.htm"
You can filter out folder in this way:
Get-ChildItem $basedir -Force | ? { -not $_.psiscontainer } | ... rest of your code ...
in powershell V3
Get-ChildItem $basedir -Force -file | ... rest of your code ...
What C.B. said. Another option, since you want only .htm files, would be filtering those files in Get-ChildItem:
Get-ChildItem $basedir -Filter "*.htm" -Force | ...