Option Explicit
Dim HyperVServer
Dim VMName
Dim NewKVPName
Dim NewKVPData
Dim WMIService
Dim VSManagementService
Dim VM
Dim KVP
Dim NewKvpExchangeDataItem
Dim NewKvpExchangeDataItemArray
Dim Result
Dim Job
Dim InParam
Dim OutParam
'Prompt for the Hyper-V Server to use
HyperVServer = InputBox("Specify the Hyper-V Server to be used:")
'Prompt for the VM to use
VMName = InputBox("Specify the name of the virtual machine to create the KVP on:")
'Get name for new KVP
NewKVPName = InputBox("Specify the name for the new KVP:")
'Get data for new KVP
NewKVPData = InputBox("Specify the value for the new KVP:")
'Get an instance of the WMI Service in the virtualization namespace.
Set WMIService = GetObject("winmgmts:\\" & HyperVServer & "\root\virtualization")
'Get the VirtualSystemManagementService object
Set VSManagementService = WMIService.ExecQuery("SELECT * FROM Msvm_VirtualSystemManagementService").ItemIndex(0)
'Get the VM object that we want
Set VM = (WMIService.ExecQuery("SELECT * FROM Msvm_ComputerSystem WHERE ElementName='" & VMName & "'")).ItemIndex(0)
'Get the KVP Object for the virtual machine
Set KVP = (VM.Associators_("Msvm_SystemDevice", "Msvm_KvpExchangeComponent")).ItemIndex(0)
' Initialize a new Msvm_KvpExchangeDataItem object
Set NewKvpExchangeDataItem = WMIService.Get("Msvm_KvpExchangeDataItem").SpawnInstance_()
'Populate the KVP data item
NewKvpExchangeDataItem.Name = NewKVPName
NewKvpExchangeDataItem.Data = NewKVPData
NewKvpExchangeDataItem.Source = 0
'Put new KVP data item in a correctly formatted array
NewKvpExchangeDataItemArray = Array(1)
NewKvpExchangeDataItemArray(0) = NewKvpExchangeDataItem.GetText_(1)
'Setup the input parameter list
Set InParam = VSManagementService.Methods_("AddKvpItems").InParameters.SpawnInstance_()InParam.TargetSystem = VM.Path_.Path
InParam.DataItems = NewKvpExchangeDataItemArray
'Execute the method and store the results in OutParam
Set OutParam = VSManagementService.ExecMethod_("AddKvpItems", InParam)
'Check to see if the job completed synchronously
if (OutParam.ReturnValue = 0) then
Wscript.Echo "KVP data item created."
elseif (OutParam.ReturnValue <> 4096) then
Wscript.Echo "Failed to create KVP data item."
else
'Get the job object
set Job = WMIService.Get(OutParam.Job)
'Wait for the job to complete (3 == starting, 4 == running)
while (Job.JobState = 3) or (Job.JobState = 4)
Wscript.Echo Job.PercentComplete
WScript.Sleep(1000)
'Refresh the job object
set Job = WMIService.Get(OutParam.Job)
Wend
'Provide details if the job fails (7 == complete)
if (Job.JobState <> 7) then
Wscript.Echo "Failed to create KVP data item."
Wscript.Echo "ErrorCode:" & Job.ErrorCode
Wscript.Echo "ErrorDescription:" & Job.ErrorDescription
else
Wscript.Echo "KVP data item created."
end If
end if