Bulk changing virtual hard disk path

I received this in email today:

“I have XCOPY’d a bunch of VHDX files from one volume to another on WS2016.    What’s the easiest / fastest way to fix up the paths for the VM’s???”

The answer to this is quite simple.  Open PowerShell and run:

$oldPath = "C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks"
$newPath = "D:"
get-vm | Get-VMHardDiskDrive | ? path -Like $oldPath* | %{Set-VMHardDiskDrive -VMHardDiskDrive $_ -Path $_.path.Replace($oldPath, $newPath)}

A couple of details on this answer:

  1. PowerShell is wonderful for these kinds of bulk operations
  2. While we do not allow you to edit the virtual hard disk path on a saved virtual machine using Hyper-V manager – we do allow you to do this through PowerShell.  In fact – there are a lot of things that are blocked in Hyper-V manager that are possible through PowerShell.