Use PowerShell to Create and Launch a new Hyper-V Virtual Machine

I’m in the midst of a lot of testing, so needed the ability to quickly spin up Hyper-V virtual machines…

This is nothing special, but I threw together the following script, which gives you a nice little template, suitable for Windows 11.

# Create a new Gen2 Hyper-V VM (with Windows 11 in mind)
# Configure the VM, Start and then Launch it.
# Love from James Vincent
# January 2024

$VMName = read-host "Enter the name of the VM"
$ISO = read-host "Enter the path to your ISO file"
$VMPath = "C:\VMs"

New-VM -Name "$VMName" -MemoryStartupBytes 4GB -Path "$VMPath" -Generation 2 -NewVHDPath "$VMPath\$VMName\Virtual Hard Disks\$VMName.vhdx" -NewVHDSizeBytes 60GB -SwitchName "Default Switch"
Set-VM -Name "$VMName" -ProcessorCount 4
Add-VMDvdDrive -VMName "$VMName" -Path "$ISO"
Get-VMDvdDrive -VMName "$VMName"
Set-VMFirmware "$VMName" -EnableSecureBoot On
Set-VMFirmware -VMName "$VMName" -FirstBootDevice $(Get-VMDvdDrive -VMName "$VMName")
$DefaultBootOrder = Get-VMFirmware -VMName $VMName | Select-Object -ExpandProperty BootOrder
$BootOrder = $DefaultBootOrder | Where-Object { $_.BootType -ne "Network" }
Set-VMFirmware -VMName $VMName -BootOrder $BootOrder
Set-VMKeyProtector -VMName "$VMName" -NewLocalKeyProtector
Enable-VMTPM -VMName "$VMName"
Set-VM -Name "$VMName" -CheckpointType Disabled
Start-VM -Name "$VMName"
vmconnect localhost $VMName

It works really well in conjunction with this script from Andrew Taylor, which will download the latest Windows ISO and inject an Autopilot JSON file for you…

James avatar

Leave a Reply

Your email address will not be published. Required fields are marked *