Share via


Powershell Script - Cleaning up your hyper-v environment after a lab

so this is part 2

this will....

 

1. enumerate the VM's on the system

2. turn them off

3. delete them

4. enumerate the virtual switches

5. delete them

6. delete the VM Storage Location (it will prompt you for the path)

this should leave your system nice and ready for the next lab :)

 

here is the code.....

 

# Author: John McCabe

# Email: johm@microsoft.com

# Twitter: @mccabej

 

$vmstoreloc = Read-host "Please Enter the Root path of the Virtual Machines and press enter"

#Get the list of VM's
write-host "Gathering List of Virtual Machines"

$getvms = get-wmiobject -class msvm_computersystem -namespace "root\virtualization" -computername "localhost" |where {$_.caption -ne "Hosting Computer System"}

if ($getvms -ne $null)
{
 #Turn off the VM's
 write-verbose "Forcing Virtual Machines off"
 foreach ($vm in $getvms)
 {
  $vm.requeststatechange(3) |out-null
 }

 #Delete the VM's
 write-host "Deleting virtual machines"
 Foreach ($vm in $getvms)
 {
  $vmmgt = get-wmiobject -class "Msvm_VirtualSystemManagementService" -namespace "root\virtualization" 
  $result = $vmmgt.DestroyVirtualSystem($VM)

 if($result.ReturnValue -eq 4096)
 { 
       $job = [wmi]$result.Job 
 }
      
     while($job.jobstate -lt 7)
 {
  $job.get()
 } 
      
     return $job.ErrorCode 
 
 } 
}
else
{
 write-host "No VM's Found"
}

#Delete the Switch's
$virtualswitch = get-wmiobject -namespace root\virtualization -class MSVM_VirtualSwitch

if ($virtualswitch -ne $null)
{
write-host "Deleting Switches..."
$switchobj = get-wmiobject -namespace root\virtualization -class Msvm_VirtualSwitchManagementService

 

foreach ($vs in $virtualswitch)
{
 $switchobj.deleteswitch($vs)
}

}
else
{
 write-host "No Virtual Switches Found"
}

#delete the folder which stores the vm's

write-host "Emptying Directory Contents....."
get-childitem $vmstoreloc |remove-item -recurse -force
if ($? -eq $true)
{
 write-host "Directory Successfully Cleared"
}
else
{
 write-host "Problems encountered clearing $vmstoreloc please do a manual check"
}

remove-item $vmstoreloc

if ($? -eq $true)
{
  write-host "Successfully removed directory $vmstoreloc"
}
else
{
 write-host "Problem removing $vmstoreloc please remove manually"
}