Powershell Reporting Trick

Here is a little trick I keep re-using to output csv files of data from vCenter.

[powershell]$reportArray = @()

foreach($cluster in get-cluster){ foreach($vm in get-vm -Location $cluster){ foreach($ds in get-DataStore -VM $vm.name){ $reportArray += New-Object PSObject -Property @{ ClusterName = $cluster.Name VMName = $vm.Name DatastoreName = $ds.name FreeSpaceMB = $ds.FreeSpaceMB CapacityMB = $ds.CapacityMB } echo $cluster.name $vm.name $ds.name $ds.FreeSpaceMB $ds.CapacityMB } } }

$reportArray | Sort-Object -Property ClusterName,VMName,DatastoreName | Export-Csv “DataStoreUsage.csv” -NoTypeInformation -UseCulture[/powershell]

The important bit is [powershell] $reportArray += New-Object PSObject -Property @{ ClusterName = $cluster.Name VMName = $vm.Name DatastoreName = $ds.name FreeSpaceMB = $ds.FreeSpaceMB CapacityMB = $ds.CapacityMB } [/powershell] I cant remember where I saw it but it creates an object with properties with the information I want to use that I can then sort, filter and send places.

I used it again today: [powershell] $reportArray = @()

Get-VM | % {$vmguest = Get-VMGuest -VM $_ ; $reportArray += New-Object PSObject -Property @{ VMName = $.name GuestOS = $vmguest.OSFullName IPAddress = [string]::Join(“ ”, $vmguest.IPAddress) HOSTNAME = $.guest.hostname } }

$reportArray | Out-GridView [/powershell] Using the lovely Out-GridView commandlet Out gridview

UPDATE Turns out you need this update for the New-Object PSObject -Property bit to work.