Powershell Oneliner #4

Yesterday, alanrenouf asked the following question on the VMware Community VI Toolkit forums:

Is there a way (preferably a one-liner) to get a list of vm’s and the number of snapshots per vm?

Here’s a script that will get that info:

$VC = Connect-VIServer $VCServerName
$vms = Get-VM
$myCol = @()
ForEach ($vm in $vms)
{
  $snapshots = Get-Snapshot -VM $vm
  $myObj = "" | Select-Object VM, NumSnapshots
  $myObj.VM = $vm.name
  $myObj.NumSnapshots = ($snapshots | measure-object).count
  $myCol += $myObj
}
$myCol | Where-Object{$_.NumSnapshots -gt 0} | Sort-Object VM | Format-Table -AutoSize

And here’s a one-liner that does the same thing: 

Get-VM |
  Where{(Get-SnapShot -VM $_ | Measure-Object).Count -gt 0} |
  Format-Table Name, `
  @{Label="NumSnapshots";Expression={(Get-Snapshot -VM $_ | Measure-Object).Count}}

»crosslinked«