Remove a Virtual Machine and Delete VHDs with PowerShell and Hyper-V Server 2012 R2

So I’ve got a pretty simple lab.  I have one on my desk running Hyper-V Server 2012 R2 and one on the laptop under Windows 8.1.

There is no SCVMM in this equation because to be quite honest, each resource has 8 gb of ram.  It’s a home lab but it meets my needs.

So I tend to spin machines up and down.   I delete them from time to time. 

Deleting makes a mess.   Typically you delete the VM Then go digging for the corresponding VHD file to delete it too.

But with the new Hyper-V Cmdlets all this gets easier.   Because wouldn’t it make SENSE to delete those old VHD files as you delete the machine? 

Well not in Production.  (NOTE! DON’T YOU DARE DO THIS IN PRODUCTION!)

So it’s quite easy to find out the VHD files attached to a VM.   Just execute this Cmdlet

GET-VM –vmname CONTOSO-DEMO | GET-VMHardDiskDrive

Looking at the output I can see the path to the Vhd’s in question


I can simply remove those VHD files with a Remove-Item by specifying the path provided in this object.

GET-VM –vmname CONTOSO-DEMO | GET-VMHardDiskDrive | Foreach { Remove-item –path $-.Path }

But why Foreach?  Couldn’t I just pipe it through? 

The reason I am going with Foreach is I would like to add a little more.   You see when I kill my lab machines (when I am done with them) I do the following

  • Unceremoniously cut the Machine with a STOP-VM
  • Delete the VHD’s
  • Delete the VM

So I’m actually going to do all all this at once.  We’ll extend that Foreach loop

GET-VM –vmname CONTOSO-DEMO | GET-VMHardDiskDrive | Foreach { STOP-VM –vmname $-.VMname; Remove-item –path $-.Path; REMOVE-VM –vmname $-.Vmname }

I can even wrap a parameter and make this as a script or function to make purging even easier.





GET-VM –vmname $Vmname | GET-VMHardDiskDrive | Foreach { STOP-VM –vmname $-.VMname; Remove-item –path $-.Path; REMOVE-VM –vmname $-.Vmname }



And now I can just plug in something like this to clean up my old lab mess!


…and let the computer do all the work.

Remember the Power of Shell is in YOU

the Energized Tech

Leave a Reply