In order to retrieve a list of virtual machines which are reporting t the issue ‘Virtual machine disks consolidation is needed’ we can invoke the Get-VM cmdlet to determine if a virtual machine consolidation is required.
$VMs = Get-VM | Where-Object {$_.ExtensionData.RunTime.ConsolidationNeeded}
To consolidate snapshots for a collection of virtual machines we can now perform the following, where the virtual machine consolidation will complete before invoking the script block on the next object.
ForEach ($VM in $VMs) { (Get-VM $VM).ExtensionData.ConsolidateVMDisks() }