Deleting a saved state through WMI [Hyper-V]

I received this question from our product support team this week:

“How do you delete the saved state of a virtual machine through WMI?”

What they are refering to here is the fact that – through the Hyper-V Manager user interface – you can delete the saved state of a virtual machine that is in a saved state:


The most common reason for wanting to do this is because you have moved a virtual machine (with a saved state) to another computer – and the saved state is no longer compatible.

The problem is that there is no “delete saved state” WMI API.  The reason for this is that – at a WMI level – to delete a saved state all you need to do is to “turn off” the virtual machine.  Here is a sample script that turns off a virtual machine:

# Function for handling WMI jobs / return values
Function ProcessResult($result, $successString, $failureString)
   #Return success if the return value is "0"
   if ($result.ReturnValue -eq 0)
      {write-host $successString} 
   #If the return value is not "0" or "4096" then the operation failed
   ElseIf ($result.ReturnValue -ne 4096)
      {write-host $failureString "  Error value:" $result.ReturnValue}
      {#Get the job object
      #Provide updates if the jobstate is "3" (starting) or "4" (running)
      while ($job.JobState -eq 3 -or $job.JobState -eq 4)
         {write-host $job.PercentComplete "% complete"
          start-sleep 1
          #Refresh the job object
       #A jobstate of "7" means success
       if ($job.JobState -eq 7)
          {write-host $successString}
          {write-host $failureString
          write-host "ErrorCode:" $job.ErrorCode
          write-host "ErrorDescription" $job.ErrorDescription}
# Prompt for the Hyper-V Server to use
$HyperVServer = Read-Host "Specify the Hyper-V Server to use (enter '.' for the local computer)"
# Prompt for the virtual machine to use
$VMName = Read-Host "Specify the name of the virtual machine"
# Get the management service
$VMMS = gwmi -namespace root\virtualization Msvm_VirtualSystemManagementService -computername $HyperVServer
# Get the virtual machine object
$VM = gwmi MSVM_ComputerSystem -filter "ElementName='$VMName'" -namespace "root\virtualization" -computername $HyperVServer
# Turn off the virtual machine
$result = $VM.RequestStateChange(3)
# Check to see that we were successful
ProcessResult $result "The virtual machine has been turned off." "Failed to turn off the virtual machine."

If you run this on a running virtual machine, the virtual machine will be turned off.  But if you run this on a virtual machine that is in a saved state – the saved state will be deleted instead.