Hyper-V How To: Delete a VM using Script

Some friends here on the Hyper-V team shared a PowerShell 2.0 script for deleting a VM:

# Delete a VM

param(
    [string]$VMName = $(throw "Must specify name of virtual machine to delete")
)
#Obtain the VM object that we are going to destroy
$query = "SELECT * FROM Msvm_ComputerSystem WHERE ElementName='" + $VMName + "'"
$VM = gwmi -query $query -namespace "root\virtualization"
#obtain the VirtualSystemManagementService class
$VSMgtService = get-wmiobject -class "Msvm_VirtualSystemManagementService" -namespace "root\virtualization"
#Destroy the virtual computer system.
$result = $VSMgtService.DestroyVirtualSystem($VM)

if($result.ReturnValue -eq 4096){
    # A Job was started, and can be tracked using its Msvm_Job instance
    $job = [wmi]$result.Job
    # Wait for job to finish
    while($job.jobstate -lt 7){$job.get()}
    # Return the Job's error code
    return $job.ErrorCode
}
# Otherwise, the method completed
return $result.ReturnValue

 

For more info on how to use PS cmdlets see: https://www.microsoft.com/technet/scriptcenter/topics/msh/cmdlets/index.mspx

See also James O’Neil’s New and improved PowerShell Library for Hyper-V. Now with more functions and... documentation!

For all 35 sample Hyper-V PS1 scripts in a zipfile, go to: Hyper-V%20PowerShell%20Example%20Scripts.zip-download