Passing PowerShell Output to CSV/Excel - excel

I previously had asked a question regarding adding together files and folders with a common name and having them summed up with a total size (Sum of file folder size based on file/folder name). This was successfully answered with the PS script below:
$root = 'C:\DBFolder'
Get-ChildItem "$root\*.mdf" | Select-Object -Expand BaseName |
ForEach-Object {
New-Object -Type PSObject -Property #{
Database = $_
Size = (Get-ChildItem "$root\$_*\*" -Recurse |
Measure-Object Length -Sum |
Select-Object -Expand Sum ) / 1GB
}
}
This now leaves me with a list that is ordered by the 'Database' Property by default. I have attempted to use a Sort-Object suffix to use the 'Size' property with no joy. I have also attempted to use Export-Csv with confounding results.
Ideally, if I could pass the results of this script to Excel/CSV so I can rinse/repeat across multiple SQL Servers and collate the data and sort within Excel, I would be laughing all the way to the small dark corner of the office where I can sleep.
Just for clarity, the output is looking along the lines of this:
Database Size
-------- ----
DBName1 2.5876876
DBName2 4.7657657
DBName3 3.5676578

Ok, it was one pipe character that I had missed when using the Export-csv function. This resolved my problem.
$root = 'C:\DB\Databases'
Get-ChildItem "$root\*.mdf" | Select-Object -Expand BaseName |
ForEach-Object {
New-Object -Type PSObject -Property #{
Database = $_
Size = (Get-ChildItem "$root\$_*\*" -Recurse |
Measure-Object Length -Sum |
Select-Object -Expand Sum ) / 1GB
}
} | Export-Csv 'C:\Test\test.csv'

Related

Display Data on Two Columns Within Excel

I am trying to display data within an Excel document where Column A displays the server name and column B displays the .NET version. I'm running into an issue exporting to a .csv because it says that the file path does not exist. I would like some guidance on how I can resolve that issue and how I can display data on the two columns within Excel.
$Servers =
(
"test"
)
foreach ($Server in $Servers)
{
Invoke-Command -ComputerName $Server -ScriptBlock {
Write-Output "$(hostname)"
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse | Get-ItemProperty -Name Version,Release -EA 0 | where { $_.PSChildName -match '^(?!S)\p{L}'} | select PSChildName, Version, Release | Select -ExpandProperty Version | Sort-Object Version | Export-Csv -Path C:\Users\User\Desktop\example.csv
}
The main issue is that you're using Export-Csv on the remote hosts since it is inside the Invoke-Command script block, and the likeable error is because the path you are using as export doesn't exist on those hosts.
It's also worth noting that Invoke-Command can run in parallel, -ComputerName as well as -Session can take an array, this removes the need for the foreach loop as well as it is much faster / efficient.
Invoke-Command -ComputerName $servers -ScriptBlock {
Write-Host "Working on $($env:COMPUTERNAME)..."
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse |
Get-ItemProperty -Name Version, Release -EA 0 |
ForEach-Object {
if($_.PSChildName -notmatch '^(?!S)\p{L}') {
return # skip this
}
[pscustomobject]#{
HostName = $env:COMPUTERNAME
Version = $_.Version
}
} | Sort-Object Version
} -HideComputerName | Select-Object * -ExcludeProperty RunspaceID |
Export-Csv -Path C:\Users\User\Desktop\example.csv -NoTypeInformation

PowerShell export "Get-volume" to excel/csv

I used the below one it gives somewhat different in excel ,please help me on this
#Disk Space
Get-Volume
$results = Get-Volume | Export-Csv -Path C:\temp\software1.csv
Note: I need health check , Drive Name, Free space , size, disk type in excel
Thanks in advance friends :)
Generally speaking, when you run a powershell command it only shows what sections are deemed as important. If you take the same command and pipe it to format-list (or "ft" for short) you will get everything.
Get-Volume | ft
When exporting it exports everything.
Also, you need to add the paramater -NoTypeInformation to get rid of the first row.
To only get certain values, you will just pipe it using select.. something like this:
Get-Volume | select HealthStatus, DriveLetter, SizeRemaining,DriveType | Export-Csv -NoTypeInformation -Path C:\temp\software1.csv
Also, there is no need to do $results = get-volume... This pushes the output into the variable $results. This would be applicable if you wanted to recall the variable later. So, you could also do something like this..
$results = Get-Volume
$results | select HealthStatus, DriveLetter, SizeRemaining, DriveType | Export-Csv -NoTypeInformation -Path C:\temp\software1.csv
Keep in mind you need to have the Import-Excel Module loaded but you should be able to use this to output to Excel.
#check-DiskSpace_FSs.ps1
import-module activedirectory
$dc = "domainController09"
$currentDate = get-date -Format yyyyMMdd_HHmm
$path = "\\UNC\export\FileServer_DiskSpace\FileServer_DiskSpace_$currentDate.xlsx"
$smtpServer = "10.10.10.10"
$from = "me#somewhere.com"
$to = "me#somewhere.com"
$subject = "Server FS diskspace - $date"
$ServerFSs = get-adcomputer -Server $dc -SearchBase "OU=fs,OU=Server,DC=somewhere,DC=com" -filter * | select name | sort Name
$DriveSize = foreach ($FS in $somewhereFSs)
{
get-WmiObject win32_logicaldisk -ComputerName $FS.name -Filter "Drivetype=3" | select SystemName,DeviceID,#{n="TotalSize(GB)";e={$_.Size / 1gb -as [int] }}`
,#{n="FreeSize(GB)";e={$_.freespace / 1gb -as [int] }}`
,#{n="FreeSize(%)";e={[int]($_.Freespace*100/$_.Size)}},VolumeName | Export-Excel -Path $path -append -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter
}
Send-Mailmessage -smtpServer $smtpServer -from $from -to $to -subject $subject -Attachments $path -priority High

Powershell get infos about files and try to Export them

I try do write a script where i can choose a folder and powershell shows me the Name, Size,.... of all the files in that folder. After that powershell should export the Informations in a Excel Table.
But im stuck and dont know what to do :C
Here is my code that i tried to build
Function Get-Folder($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")|Out-Null
$foldername = New-Object System.Windows.Forms.FolderBrowserDialog
$foldername.Description = "Select a folder"
$foldername.rootfolder = "MyComputer"
if($foldername.ShowDialog() -eq "OK")
{
$folder += $foldername.SelectedPath
}
return $folder
}
$a = Get-Folder
$folder = $a
Get-ChildItem -Path $folder | SELECT Name, #{Name="Size In KB";Expression={$_.Length / 1Kb}}, Attributes, LastaccessTime, #{n='Owner';e={(get-acl $_.Fullname).Owner}}| Format-Table -AutoSize
Export-Csv "C:\Users\DZimmermann\Desktop\Test.csv" -Delimiter ";" -Append
As commented, using Format-Table -AutoSize simply outputs the info in a table format to console. It returns nothing, so there is nothing to write in the csv file..
Doing like this will create the CSV file and writes the info in there:
Get-ChildItem -Path $folder |
Select-Object Name,
#{Name="Size In KB";Expression={$_.Length / 1Kb}},
Attributes, LastaccessTime,
#{n='Owner';e={(get-acl $_.Fullname).Owner}} |
Export-Csv "C:\Users\DZimmermann\Desktop\Test.csv" -Delimiter ";"
This will not get you the info on screen. If you also want that, capture the result in a variable first:
$result = Get-ChildItem -Path $folder |
Select-Object Name,
#{Name="Size In KB";Expression={$_.Length / 1Kb}},
Attributes, LastaccessTime,
#{n='Owner';e={(get-acl $_.Fullname).Owner}}
#output on screen
$result | Format-Table -AutoSize
# write the CSV file:
$result | Export-Csv "C:\Users\DZimmermann\Desktop\Test.csv" -Delimiter ";"
P.S. judging by the title of this question, I think you only want info about Files, not Directories..
If that is the case, add -File switch to the Get-ChildItem cmdlet (for PS 3 and up). For PS versions below 3 use
Get-ChildItem -Path $folder | Where-Object { !$_.PSIsContainer }

Export CSV Writes Results to Single Line, How Do I get Multiple Lines?

I am looking for duplicates on a share drive so I can let the users know and they can clean it up before we use anything automated. My largest duplicate is close to 400 copies, but the info is all on a single line.
My query is getting the correct results:
$a = Get-ChildItem -Path "S:\" -File -Recurse |
Select-Object -Property Fullname, #{N='Hash';E={(Get-FileHash $_.FullName).Hash}}
$cnt = $a | Group-Object -Property Hash
$cnt |
Select-Object Count, #{N='FullName';E={($_.Group).FullName}}, #{N='Hash';E={($_.Group).Hash}} |
Sort-Object -Property Count -Descending |
Export-Csv C:\Temp\S_Drive_Counts.csv
Here is an example of my results where each entry is on a single line:
"Count","FullName","Hash"
"2","S:\Generation 1\Certification Authority.txt S:\Generation 2\Certification Authority.txt","498868376A5377F731593E9F96EC99F34C69F47537C81B9B32DBAC9321462B83 498868376A5377F731593E9F96EC99F34C69F47537C81B9B32DBAC9321462B83"
I need to pass this info on though, so I'd like to have each entry on a line by itself, similar to this:
"Count","FullName","Hash"
"2","S:\Generation 1\Certification Authority.txt","498868376A5377F731593E9F96EC99F34C69F47537C81B9B32DBAC9321462B83"
"2","S:\Generation 2\Certification Authority.txt","498868376A5377F731593E9F96EC99F34C69F47537C81B9B32DBAC9321462B83"
I can do some string manipulation to the CSV if needed, but I am looking for a way to get it in the correct format before exporting to the CSV.
Unroll your groups. Also, make better use of the pipeline.
Get-ChildItem -Path 'S:\' -File -Recurse |
Select-Object Fullname, #{n='Hash';e={(Get-FileHash $_.FullName).Hash}} |
Group-Object Hash |
ForEach-Object {
$cnt = $_.Count
$_.Group | Select-Object #{n='Count';e={$cnt}}, FullName, Hash
} |
Sort-Object Count, Hash, FullName -Descending |
Export-Csv 'C:\Temp\S_Drive_Counts.csv' -NoType

How do I add another column to a System.Object using a list in Powershell?

I am making a script to query active directory via powershell and pull all computers that contain a username in the description field, then filter that list with only computers last logged in the past 14 days.
This is what I have so far:
$queryAD = Get-ADComputer -SearchBase 'OU=West Division,DC=cable,DC=comcast,DC=com' -Properties Name, Description -Filter {(Name -like "WA*") -and (Description -like $wildCard)} | Select-Object Name, Description
$lastLogon = $queryAD | Select-Object -ExpandProperty Description | %{$_.replace(("$NTname" + ";"),"").split(";")[0]} | %{get-date $_ -format d}
I'd like to add the list generated from $lastLogon to $queryAD, right now $queryAD is returning two columns with headers Name and Description. I need a third header added called Last Logon Date and contain the list in $lastLogon. Please advise.
You could assign the values to an array of objects to make your output cleaner (if this method is providing you the data you want) like so:
$queryAD = Get-ADComputer -SearchBase 'OU=West Division,DC=cable,DC=comcast,DC=com' -Properties Name, Description -Filter {(Name -like "WA*") -and (Description -like $wildCard)} | Select-Object Name, Description
$computer_list = #()
foreach($computer in $queryAD) {
$computer_info = New-Object PSObject -Property #{
Name = $computer.Name
Description = $computer.Description
LastLogonDate = $computer | Select-Object -ExpandProperty Description | %{$_.replace(("$NTname" + ";"),"").split(";")[0]} | %{get-date $_ -format d}
}
$computer_list += $computer_info
}
in which case $computer_list will contain all of the info you're gathering in tidy objects.
...but this method seems overcomplicated. Look into this blog entry by Matt Vogt for a better way to query for old machines in AD.

Resources