PowerShell

Create Hyper-V VMs with PowerShell (Single, Multiple)

In case you have Hyper-V in use, then you are in the right place. In this blog post I will show you how to create VMs in Hyper-V. I will also show how to create multiple Hyper-V VMs at the same time using PowerShell. It’s great to see PowerShell showing what it can do here as well: Automation. Let’s start.

Create a Hyper-V Guest with PowerShell

First of all we need the cmdlets for Hyper-V. These can be called quite easily. We retrieve all of them from the Hyper-V module.

Get-Command  -Module Hyper-V

Fine, let’s move on. We need the New-VM Cmldet and a few parameters of it. Just modify the hashtable and enter parameter values of your choosing. It is assumed that you have already created a Hyper-V Switch and you have an installation medium.

$vms = @{

    Name = 'Server001'
    Generation = '2'
    MemoryStartupBytes = 2GB
    NewVHDPath = 'c:\temp\server001.vhdx'
    NewVHDSizeBytes = 40GB
    SwitchName = 'Default Switch'

}

New-VM @vms
 
Add-VMDvdDrive `
-VMName $vms.Name `
-Path C:\Software\de_windows_server_2019_updated_sep_2020_x64_dvd_da9064e2.iso

Set-VMFirmware -VMName $vms.Name `
-FirstBootDevice ((Get-VMFirmware -VMName $vms.Name).BootOrder | 
Where-Object Device -like *DvD*).Device

How do you know this worked?

Get-VM 

That’s it. Mission accomplished. We have successfully created a VM in Hyper-V with PowerShell that will boot with the given installation medium.

Create multiple Hyper-V Guests with PowerShell

PowerShell is a script language that focuses on automating tasks, In this example I show you how you can create Hyper-V guests at once originating from a simple array. The values, respectively computernames, are separated by comma. Give it a try, you can easily build on this example.

On your mark, get set, go 😉

'Server002','Server003' |
ForEach-Object {

New-VM `
-Name $_ `
-Generation '2' `
-MemoryStartupBytes 2GB `
-NewVHDPath "c:\temp\$_.vhdx" `
-NewVHDSizeBytes 40GB `
-SwitchName 'Default Switch'  

}

As you can see we now have created multiple VMs.

You may ask now “Hey there is something missing”. You are right. Normally, we need to insert a DVD or ISO file which usually acts as the installation medium. Automating this is difficult because each VM needs a different medium. You can find the commands to add a DVD drive and set the Firmware in the first example of this blog post.

Hope you enjoyed it! See you!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.