Why

Adding a disk to a VM is not a big issue. I can use Hyper-V console or Windows Admin Center or PowerShell. But because I need to do it on a frequent basis and it’s boring I wanted to find a better way.

Just a reminder - how to add VHD to a VM:

HyperV

Select New, and then name it, select path and proper options.

WAC

Then again, fill in proper path and options. In PowerShell - it’s sligthly better:

#Create VHD in given path
New-VHD -Path 'Path' -Dynamic -SizeBytes 100GB
#Attach it to a VM
Add-VMHardDiskStrive -VMName 'VM1' -ComputerName 'HyperVHost' -Path 'Path'

There are two problems with this. First - I need to know WHERE to put the files for given VM. In general I have all disks on the same CSV - along with VM configuration. Second - it’s boring :)

The Idea

So, I wanted to speed this up a bit. What I know?

  1. Use Invoke-Command
    • I will be able to connect to different versions of Hyper-V
    • I will be able to use optional Credential parameter to connect to Hyper-V hosts in different domains. Or run it from unprivilged powershell session.
    • This will also work from PowerShell Core
  2. Gather some basic info about disks of given VM.
    • This will give me current VM path location
    • And also the number of current VHDs. (remember the <VMName>_disk<number>.vhdx part?
  3. Create VHD and then attach it to a VM.

Here’s the code:

What’s next? Well a VHD needs to be formatted right? Booring:) Glad I have this Format Drive. Remotely.

Final code

Well if I combine both of these functions I can do it in one swing. For multiple disks at once!

Here’s the output: