有没有办法使用PowerShell从Hyper-V获取VM操作系统名称?

时间:2016-06-29 10:20:31

标签: powershell automation virtual-machine wmi hyper-v

我在HYPER-V主机上编写脚本以获取VM客户信息。有没有办法使用PowerShell从Hyper-V获取VM操作系统名称?

有几个使用{{1}}的示例,但由于域限制,我应该直接从Hyper-V获取此信息。

另外我使用了powershell的hyper-v模块,但我看不到任何与操作系统相关的cmdlet。

2 个答案:

答案 0 :(得分:1)

除非您使用SCVMM,否则无法通过Hyper-V PowerShell cmdlet提供Guest OS详细信息。

您必须像已经找到的那样查询来宾本身。

答案 1 :(得分:1)

这可以从访客内在交换项中检索。

# Filter for parsing XML data
filter Import-CimXml 
{ 
   # Create new XML object from input
   $CimXml = [Xml]$_ 
   $CimObj = New-Object -TypeName System.Object 

   # Iterate over the data and pull out just the value name and data for each entry
   foreach ($CimProperty in $CimXml.SelectNodes("/INSTANCE/PROPERTY[@NAME='Name']")) 
      { 
         $CimObj | Add-Member -MemberType NoteProperty -Name $CimProperty.NAME -Value $CimProperty.VALUE 
      } 

   foreach ($CimProperty in $CimXml.SelectNodes("/INSTANCE/PROPERTY[@NAME='Data']")) 
      { 
         $CimObj | Add-Member -MemberType NoteProperty -Name $CimProperty.NAME -Value $CimProperty.VALUE 
      } 

   # Display output
   $CimObj 
} 

# 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 virtual machine object
$query = "Select * From Msvm_ComputerSystem Where ElementName='" + $VMName + "'"
$Vm = gwmi -namespace root\virtualization\v2 -query $query -computername $HyperVServer

# Get the KVP Object
$query = "Associators of {$Vm} Where AssocClass=Msvm_SystemDevice ResultClass=Msvm_KvpExchangeComponent"
$Kvp = gwmi -namespace root\virtualization\v2 -query $query -computername $HyperVServer

Write-Host
Write-Host "Guest KVP information for" $VMName

# Filter the results
try {
    $Kvp.GuestIntrinsicExchangeItems | Import-CimXml | where Name -eq "OSName"
}
catch {
    Write-Host "Not found"
}

来自Ben Armstrong’s Virtualization Blog