Hyper-V How To: Change VHD using Script

Some friends here on the Hyper-V team shared a PowerShell 2.0 script for changing the VHD in a VM:

# Change VHD in drive

param(
    [string]$vmName = $(throw "Must specify virtual machine name"),
    [string]$oldPath = $(throw "Must specify the current path to VHD attached to drive"),
    [string]$newPath = $(throw "Must specify the path to new VHD")
)

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

# Get this Virtual Machine's current virtual system setting data
$vssd = gwmi -namespace root\virtualization `
    -query "Associators of {$vm} where ResultClass=Msvm_VirtualSystemSettingData" |`
    where{$_.SettingType -eq 3}

# Get the associated disk resource allocation setting data
$allDisks = gwmi -namespace root\virtualization `
    -query "Associators of {$vssd} where ResultClass=Msvm_ResourceAllocationSettingData" |`
    where{$_.ResourceType -eq 21}

# Find the specific disk by the old path, and then set the new path
$disk = $allDisks | where{$_.Connection[0] -eq $oldPath}
$disk.Connection = @($newPath)

# Get the management service and modify the resource using the resource's embedded instance
$vmms = gwmi -namespace root\virtualization Msvm_VirutalSystemManagementService

$result = $vmms.ModifyVirtualSystemResources($vm,@($disk.GetText(1)))

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