Page tree
Skip to end of metadata
Go to start of metadata

With the huge popularity of virtualisation in the last 10 years, it is rare to find companies operating a modern IT infrastructure that does not include some number of virtualised servers. Microsoft's Hyper-V platform has seen widespread uptake and the versatility of Microsoft's PowerShell makes scripting and automating many operations within Hyper-V possible.

While creating a single VM and adding its VHD can be achieved easily using the GUI, this task becomes repetitive and time consuming when a number of VMs must be configured at once. In this scenario, a script can be used to automate this operation using PowerShell. The script below shows how a VHDX disk can be added to each VM, based on some assumptions:

  • This operation should be performed on all VMs on the Hyper-V host where the script is being run
  • The disk to add is a .VHDX file, with a filename matching the name of the VM
    • A VM called LAB-DC would be assumed to have a VHDX file named LAB-DC.vhdx
  • The VHDX file is located in the VM's root directory, in a subfolder called Virtual Hard Disks
    • A VM located at D:\VM\LAB-DC would have its VHDX file located within D:\VM\LAB-DC\Virtual Hard Disks
  • The VHDX file already exists and is already named with the VM name
    • VMs where the VHDX file cannot be found will result in an error being shown in the PowerShell window, which can be safely ignored if this was expected and no changes will be made to those VMs
  • The ControllerType, ControllerNumber and ControllerLocation do not need to be a specific value
    • The intended usage of this script is to add the first (potentially only) disk image to a new VHD and will usually default to adding an IDE disk to IDE Controller 0 at location 0

$vms = Get-VM
Foreach ($vm in $vms)
{
    $n = $vm.Name.ToString()
    $p = $vm.Path.Tostring()
    $vhd = $p + "\Virtual Hard Disks\" + $n + ".vhdx"
    Add-VMHardDiskDrive -VMName $n -Path $vhd
}

While the assumption is made that the VHDX file for each VM already exists, a modification could be made to the script above to create this file as part of the loop. To achieve this, use the New-VHD cmdlet to create the new file.