PowerShell script to create and attach VHD

Hi guys,

In today’s short post I’m gonna share a script I wrote for one of my demos. I had to present the new Windows Storage server and to demonstrate how to create pool’s of disks. Of course I had no intention to actually use physical disks, so naturally I showed it on Hyper-V and to demonstrate this I had to create several VHD/VHDx files and attach  them to a VM. Why not automate this?

So Here’s the script:

$VMName = read-host "Please enter VM Name:"

$NumDisks = read-host "How many disks would you like to add?"


$VM = Get-VM -Name $VMName -ErrorAction:stop

$Path = $vm.Path

for($i=1;$i -le $NumDisks;$i++){

$VHDLocation = $Path + "\StorageDisk" + $i + ".vhdx"

New-VHD -Path $VHDLocation -SizeBytes 5gb -Dynamic

Add-VMHardDiskDrive -VMName $VMName -Path $VHDLocation -ControllerType SCSI -ErrorAction:stop




Write-host "No such VM or could not add/create VHD"




Please note that I’m using try/catch here to verify that the vm actually exists.


What do you think about this post?