Thursday, July 25, 2013

Getting your VM name and OS Name with powershell

this is now part of the open source code project.. free to anyone.

Here is a function that will return the VMName and OSName of all the vm's running on your VHOST. Be aware it will not return and OSNAME if the VM is not powered on.

function Get-VMOSName

    $kec = get-ciminstance -ClassName msvm_computersystem -namespace root\virtualization\v2 | where elementname -eq $VMName | Get-CimAssociatedInstance -ResultClassName MSVM_KvpExchangeComponent -Namespace root\virtualization\v2
    $xml = [xml]"$($kec.GuestIntrinsicExchangeItems)"
    $nav = $xml.CreateNavigator().SelectSingleNode("root/INSTANCE/PROPERTY[@NAME='Name']/VALUE[child::text() = 'OSName']")
    if ($nav -ne $null)
        $nav.MoveToParent() | Out-Null
        $nav.MoveToParent() | Out-Null

#to return the OSNAME for a single VM
#get-VMOSName test1

# to return a table of the VMName and OSName of all VM's
#Note will not return an OSName is a VM is powered off.
Get-VM | Add-Member -Name "OSName" –MemberType ScriptProperty –Value {
       Get-VMOSName $this.Name
} -PassThru -Force | Select Name,OSName | format-table -autosize

No comments:

Post a Comment