Hyper-V 3: Attach multiple VHDs via PowerShell

Powershell Hyper-V Attach VHDs
We are already testing some Windows Server 8 installations and to test some of the new storage features I needed to attach a lot of VHDs to a Virtual Machine. Now with this Windows PowerShell script its very easy and fast.

Important:

  • Needs Windows Server 8 (Developer Preview)
  • Needs Hyper-V 3 (Inculded in Windows Server 8 )
  • Needs PowerShell v3 (Also included in Windows Server 8 )
$filePath = "\\storage01\VHDStorage\Virtual Hard Disks\"
$fileName = "server03-disk" # Your VHD will be called yourvhdnameX.vhdx (X = Number)
$serverName = "server03"
$controllerNumber = "0"
[int64]$vHDSizeGB = "100" # in GB
$vHDFormat = "vhdx" # vhdx or vhd
$vHDType = "Dynamic"
$numberofVHDs = "8"
 
 
for ($i=1;$i -le $numberofVHDs; $i++){
 
    $vHDPath = $filePath + $fileName + $i + "." + $vHDFormat
    New-VHD -Path $vHDPath -SizeBytes ($vHDSizeGB * 1073741824) -VHDFormat $vHDFormat -VHDType $vHDType
    Add-VMHardDiskDrive -VMName $serverName -ControllerType SCSI -ControllerNumber $controllerNumber -Path $vHDPath
 
}

The best thing overall is how you fast you can create such scripts with PowerShell v3. It took me like 10-12 minutes to get this thing done, and if you think how I would have to create and attach all of those VHDs with the wizard, I saved myself a lot of time.