Hyper-V How To: Set a Custom KVP using Script

Some friends here on the Hyper-V team shared a PowerShell 2.0 script for setting custom KVPs:

# Set a Custom KVP

param(
[string]$vmName = $(throw "Must specify virtual machine name"),
[string]$Key = $(throw "Must specify a key"),
[string]$Value = $(throw "Must specify a value")
)

$vm = gwmi -namespace root\virtualization Msvm_ComputerSystem -filter "ElementName='$vmName'"

# Get a new KVP Exchange Data Item and populate the Name, Data, and Source
$newKvpClass = [wmiclass]"root\virtualization:Msvm_KvpExchangeDataItem"
$newKvp = $newKvpClass.CreateInstance()
$newKvp.Name = $Key
$newKvp.Data = $Value
$newKvp.Source = 0 # Use 4 here if the key should not be sent to the guest

# Get the management service and set the KVP for this VM
$vmms = gwmi -namespace root\virtualization Msvm_VirtualSystemManagementService

$result = $vmms.AddKvpItems($vm, $newKvp)

if($result.ReturnValue -eq 4096){
# A Job was started, and can be tracked using its Msvm_Job instance
$job = [wmi]$result.Job
# Wait for job to finish
while($job.jobstate -lt 7){$job.get()}
# Return the Job's error code
return $job.ErrorCode
}
# Otherwise, the method completed
return $result.ReturnValue

For more info on how to use PS cmdlets see: https://www.microsoft.com/technet/scriptcenter/topics/msh/cmdlets/index.mspx

See also James O’Neil’s New and improved PowerShell Library for Hyper-V. Now with more functions and... documentation!

For all 35 sample Hyper-V PS1 scripts in a zipfile, go to: Hyper-V PowerShell Example Scripts.zip-download