Powershell Reporting Trick
October 4th 2010
Here is a little trick I keep re-using to output csv files of data from vCenter.
$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
The important bit is
$reportArray += New-Object PSObject -Property @{
ClusterName = $cluster.Name
VMName = $vm.Name
DatastoreName = $ds.name
FreeSpaceMB = $ds.FreeSpaceMB
CapacityMB = $ds.CapacityMB
}
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:
$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
Using the lovely Out-GridView commandlet

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