Delete a VM in Hyper V Using PowerShell

Find the PS script below that will delete the VM in Microsoft Hyper-v. The function accepts the parameter “vm-name”. You can additionally delete the VHD associated with the VM, though it is not advisable to do it.

function Print-Status {
  if ($? -eq $true)  {
    write-host “$actiontaken success”
  else {
    write-host “$actiontaken failed”

function Delete-HypervVM {
  param (
    [bool]$DeleteVHD = $False
  $vm = Get-VM -Name $VMName | Get-VMHardDiskDrive
  if ($? -eq $true) {
    Stop-VM -Name $VMName -ErrorAction Stop
    Print-Status (“Stop VM”)
    if ($DeleteVHD) {
      Remove-Item -Path $vm.Path -ErrorAction SilentlyContinue
      Print-Status (“Delete VHD”)
    $vhdpath=$vm.Path+ “\..\” + $VMName
    Remove-VM -Force -Name $VMName -ErrorAction SilentlyContinue
    Print-Status (“Delete VM”)
    Remove-Item -Force -Recurse $vhdpath -ErrorAction SilentlyContinue
    Print-Status (“Cleanup VM Files”)



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s