I am constantly creating virtual machines, fiddling with them for a bit and then forgetting about them. After a while I end up with a bunch of virtual machines listed in Hyper-V Manager where I have manually deleted or moved the files for half of them.
It can be a real pain to go through and clean this up. Luckily, PowerShell comes to the rescue here! With a simple PowerShell snippet I can list all the virtual machines on my system – and see which ones no longer have virtual hard disk files. I can then easily delete those virtual machines.
This snippet:
get-vm | Get-VMHardDiskDrive | %{write-host $_.VMName.PadRight(40) ":: VHD Exists :: "-NoNewline; Test-Path $_.Path}
- Gets all virtual machines on the system
- Gets the virtual hard disks on each virtual machine
- Runs Test-Path on each virtual hard disk
- Formats the results
The output on my computer is like this:
Cheers,
Ben