【发布时间】:2014-03-30 16:59:54
【问题描述】:
在 Hyper-V 2008 R2 和 Hyper-V 2012 中,我使用以下代码查找与 VHD 文件关联的 VM 名称。效果很好
函数 strGetVMname(strVHD)
设置 VMList = objWMIService.ExecQuery("SELECT * FROM Msvm_ComputerSystem Where Caption='Virtual Machine'")
For Each VirtualMachine in VMList
Set vm = GetComputerSystem(VirtualMachine.ElementName)
strQuery = "ASSOCIATORS OF {" & vm.Path_.Path & "} WHERE resultClass = Msvm_VirtualSystemSettingData"
set virtualSystemSetting = objWMIService.ExecQuery(strQuery).ItemIndex(0)
strQuery = Format1("ASSOCIATORS OF {{0}} WHERE " &_
" resultClass = Msvm_ResourceAllocationSettingData" &_
" AssocClass = Msvm_VirtualSystemSettingDataComponent " &_
" ResultRole = PartComponent " &_
" Role = GroupComponent", virtualSystemSetting.Path_.Path)
set objInstances = objWMIService.ExecQuery(strQuery)
for each Instance in objInstances
If (Instance.ResourceSubType = "Microsoft Virtual Hard Disk") Then
strMatch = InStr(1,Instance.Connection(0),strVHD,1)
If (strMatch = 1) Then
strGetVMname = VirtualMachine.ElementName
exit for
End If
End If
next
Next
结束函数
这在 Hyper-V 2012 R2 中不再起作用。我注意到 WMI 服务更改为 \.\root\virtualization\v2。所以我改变了代码
函数 strGetVMname(strVHD)
设置 VMList = objWMIService.ExecQuery("SELECT * FROM Msvm_ComputerSystem Where Caption='Virtual Machine'")
For Each VirtualMachine in VMList
Set vm = GetComputerSystem(VirtualMachine.ElementName)
strQuery = "ASSOCIATORS OF {" & vm.Path_.Path & "} WHERE resultClass = Msvm_VirtualSystemSettingData"
set virtualSystemSetting = objWMIService.ExecQuery(strQuery).ItemIndex(0)
strQuery = Format1("ASSOCIATORS OF {{0}} WHERE " &_
" resultClass = Msvm_ResourceAllocationSettingData" &_
" AssocClass = Msvm_VirtualSystemSettingDataComponent " &_
" ResultRole = PartComponent " &_
" Role = GroupComponent", virtualSystemSetting.Path_.Path)
set objInstances = objWMIService.ExecQuery(strQuery)
for each Instance in objInstances
If (Instance.ResourceSubType = "Microsoft:Hyper-V:Synthetic Disk Drive") Then
strMatch = InStr(1,Instance.Connection(0),strVHD,1)
If (strMatch = 1) Then
strGetVMname = VirtualMachine.ElementName
exit for
End If
End If
next
Next
结束函数
除了资源类型“Microsoft 虚拟硬盘”不再存在之外,一切正常。现在是“Microsoft:Hyper-V:Synthetic Disk Drive”硬盘。 当我更改代码以反映新名称时,我无法再从 Instance.Connection(0) 获取对象。 类型不匹配代码 800A000D 在同一行出现错误
谁能帮我让这个脚本在 2012 R2 中工作?或 powershell 脚本中的任何帮助
【问题讨论】:
标签: powershell wmi virtual-machine hyper-v