Hyper-V PowerShell One-Line-Challenge – Part 3

After posting my Hyper-V one-line PowerShell snippets last week – I had numerous people ask me: “Can you make this export to a CSV file?”.  How could I resist the ability to make this command even longer?  So here you are:

Get-Volume | ?{$_.DriveLetter -ne $null} | select @{N=’Drive Letter’;E={$_.DriveLetter}},@{N=’Free Space (GB)’;E={“{0:N2}” -f ($_.SizeRemaining / 1GB)}},@{N=’Space Used By VHDs (GB)’;E={$driveletter = $_.DriveLetter; “{0:N2}” -f ((Get-VMHardDiskDrive * | ? {$_.Path -match “^$driveletter” } | Get-VHD | Measure -sum FileSize | Select -exp sum)/1GB)}},@{N=’AllocatedToVHDs’;E={$driveletter = $_.DriveLetter; “{0:N2}” -f ((Get-VMHardDiskDrive * | ? {$_.Path -match “^$driveletter” } | Get-VHD | Measure -sum Size | Select -exp sum)/1GB)}} | Export-CSV VHDData.csv -NoTypeInformation

This single line of PowerShell will:

  1. Get all disks in the physical computer
  2. List the drive letters of each disk
  3. Report the free space on each disk (formatted to gigabytes)
  4. Finds all virtual hard disks that Hyper-V knows about on each disk and displays how much space they are using (formatted to gigabytes)
  5. Calculate how much space would be needed to fully expand all dynamically expanding disks
  6. Saves all of this in “VHDData.csv”