Powershell – Quickly Create VMs with Differencing Disks, and then edit them!

I’m playing with a new storage backend so I wanted to create a whole bunch of VMs, then edit them, then stop them, then start them. Here’s how I did it.

Here’s the end result.

img 577705ed3e27c

Now here’s how I did it.

$value = 1..10
$vmstore = "C:\VMDATA\VM POOL\"
$vmparent =  "C:\VMDATA\VM POOL\Server 2012R2 Parent.vhdx"
foreach ($number in $value) {
$name = "2012r2 Drf$number"
$vmstore2 = "$vmstore$name"
new-vm -name "$name" -NoVHD -Generation 2 -MemoryStartupBytes 2048MB -Path "$vmstore2"
get-vm -Name "$name" | set-vm -ProcessorCount 1
new-vhd -Path "$vmstore2\disk.vhdx" -ParentPath "$vmparent"
get-vm -name "$name" | Add-VMHardDiskDrive -ControllerType SCSI -Path "$vmstore2\disk.vhdx"
start-vm -Name "$name"
}

In the above the value is how many VMs we want.
The VMstore is of course where we will put the VM config files (and later VHDx)
The VMparent is for specify a parent difference disk which I created earlier. (server 2012 r2 fully updated and set to read only)
Then I use new-vm to create blank VMs.
I then set their processor count for fun.
Then I create a new VHD referencing a parent disk.
Finally I add the VHD to each VM and start 🙂

If I wanted to change things around I could use these commands to stop, edit, then start all the VMs.

get-vm | stop-vm
get-vm | Set-VMMemory -StartupBytes 4096MB
get-vm | Set-VMProcessor -Count 2
get-vm | start-vm

I also wanted to quickly delete them, this was a little trickier since using remove-vm only removes the config file. Luckily I quickly found this guide on how to do that with powershell.

The command I used was this:

get-vm | ? name -like "*D*" | Get-VMHardDiskDrive | foreach {remove-item -Path $_.path}
get-vm | ? name - like "*D*" | remove-vm

note: I filtered my results to make sure only VMs with the letter D in the name were removed.
source: https://ye110wbeard.wordpress.com/2014/03/07/remove-a-virtual-machine-and-delete-vhds-with-powershell-and-hyper-v-server-2012-r2/

Leave a comment

Exit mobile version