Wednesday, December 03, 2014

Using WMI and XML to Read Hyper-V Key-Value Pair Data

Here is the follow-up to the post about using DSC to set a key-value pair item for Hyper-V and its integration services.

The code sample below shows how to use WMI and XML to read the specific item from the key-value pair data.

The only real trick to this is to create a string that can be cast to XML, which just means creating the root node (kvpItems in the sample below) then inserting the string we get from WMI.

The next part is to use XPath to pick out just the item we need.  Having worked with FIM long enough I have developed a liking to XPath, but could have just as easily skipped XML and XPath and gone with a quick –like operator (though it wouldn’t be a nice).

Here’s the sample code:

###

### Get a VM

### then get its Key-Value Pair items

### then put them into an XML DOM

### then use XPath to find a specific key-value pair

###

$vmName = 'HoofHeartedVM'

do{

    Write-Verbose "$(Get-Date) Waiting for the FIM Service to reach the started state."

 

    $vm  = Get-WmiObject -Namespace root\virtualization\v2 -Class Msvm_ComputerSystem -Filter "ElementName='$vmName'"

    $kvp = Get-WmiObject -Namespace root\virtualization\v2 -Query "Associators of {$Vm} Where AssocClass=Msvm_SystemDevice ResultClass=Msvm_KvpExchangeComponent"

 

    $kvpItems = [xml]"<KvpItems>$($kvp.GuestIntrinsicExchangeItems)</KvpItems>"

    $kvpItem  = Select-Xml -Xml $kvpItems -XPath "/KvpItems/INSTANCE[PROPERTY/VALUE[.='FimServiceStatus'] and PROPERTY/VALUE[.='Running']]"

    Start-Sleep -Seconds 60

}

until($kvpItem)

 

No comments: