Search code examples
windowspowershellwmihyper-vget-wmiobject

Snapshot WMI Query returns nothing


-> $VMs = Get-WmiObject -Class "Msvm_ComputerSystem" -Namespace "root\virtualization\v2"
-> $vm = $VMs[1]
-> Get-WmiObject -Namespace "root\virtualization\v2" -Query "Associators Of {$vm} Where AssocClass=Msvm_ElementSettingData ResultClass=Msvm_VirtualSystemSettingData"

I use it that way but it returns nothing. VM has 2 checkpoints. But returns nothing.

I know the following command but need a query like above. The following command runs without error.

-> Get-VM | Get-VMSnapshot

Solution

  • [Note: The commands below all requires Powershell to be running as an admin. If it's not, you'll always gets zero results, IMX.]

    I either get no output or an error no matter how I write the query. This appears to be a pretty common problem with this class and namespace. Searching online reveals a lot of people with this problem. This looked like the best overall example/workaround.

    From that link, this does work:

    $VMs = Get-WmiObject -Namespace root\virtualization\v2 -ClassName Msvm_ComputerSystem
    $VM = $VMs[1]
    
    # This returns several results
    $VM.GetRelated('Msvm_VirtualSystemSettingData')
    
    # This returns one result
    $VM.GetRelated('Msvm_VirtualSystemSettingData','Msvm_SettingsDefineState',$null,$null,$null,$null,$false,$null)
    

    I do not see the GetRelated() method documented in the class documentation, but I believe that it's inherited from the ManagementObject.


    That said, I can get a slightly different version working with the newer CIM cmdlets (see Get-Command -Module CimCmdlets on Powershell v5.1 or 7), and I would recommend using those anyways. Get-WmiObject was superseded by the CIM cmdlets in Powershell v3. One of the big benefits has been that you no longer need to deal with the obnoxious ASSOCIATORS OF syntax from WQL. You can just use Get-CimAssociatedInstance.

    $VMs = Get-CimInstance -Namespace root\virtualization\v2 -ClassName Msvm_ComputerSystem
    $VM = $VMs[1]
    $VM | Get-CimAssociatedInstance -ResultClassName Msvm_VirtualSystemSettingData
    

    The above works for me. On the plus side, this code will also work on Powershell v6 and v7, which don't have Get-WmiObject.