Recently I have had a few comments on an old post I wrote showing a one-liner to get the VM’s disk sizes for each VM, I was asked if there was a way to export this information into a CSV file.

The easy answer is yes but what you need to do is build up a container and then add each part of the information to the container, this is quite common practice in PowerShell, its a great technique where you can basically build and populate your own information and then just add to it, once you are completed you can then take your container and export it to whatever format you wish, for example:

The one-liner mentioned in my previous post simply outputted the data one VM at a time to the screen, whilst this was great for looking at the information, when we try and export it things start to go wrong !

The new script, below, may take up more lines but is far more efficient and adaptable.

image

The script:

Connect-VIServer MYVISERVER
$MyCollection = @()
$AllVMs = Get-View -ViewType VirtualMachine | Where {-not $_.Config.Template}
$SortedVMs = $AllVMs | Select *, @{N="NumDisks";E={@($_.Guest.Disk.Length)}} | Sort-Object -Descending NumDisks
ForEach ($VM in $SortedVMs){
 $Details = New-object PSObject
 $Details | Add-Member -Name Name -Value $VM.name -Membertype NoteProperty
 $DiskNum = 0
 Foreach ($disk in $VM.Guest.Disk){
 $Details | Add-Member -Name "Disk$($DiskNum)path" -MemberType NoteProperty -Value $Disk.DiskPath
 $Details | Add-Member -Name "Disk$($DiskNum)Capacity(MB)" -MemberType NoteProperty -Value ([math]::Round($disk.Capacity/ 1MB))
 $Details | Add-Member -Name "Disk$($DiskNum)FreeSpace(MB)" -MemberType NoteProperty -Value ([math]::Round($disk.FreeSpace / 1MB))
 $DiskNum++
 }
 $MyCollection += $Details
}
$MyCollection | Out-GridView
# Export-Csv, ConvertTo-Html or ConvertTo-Xml can be used above instead of Out-Gridview

The output is listed in a strange order due to an issue with this method of using PowerShell as mentioned here.

Just a reminder that this information can also be viewed, filtered and exported using my VESI/PowerGUI PowerPack which you can download here. – Nearly 5000 downloads so far !

image