PowerShell Guide: New VM PowerShell

Updated 2020-03-13.

The following are some sample PowerShell steps to create VMs on Hyper-V.

We copy and paste the code into a new NotePad window. Then, CTRL+H to do a Find & Replace for the VM’s name and/or destination.

Standalone Hyper-V Host

$VMName = "VMName"
$VHDSize = 75GB
$HostDriverLetter = "K"
$ISOPath = "\\MgmtServer\ISOs\WinServ19B-2020-03-13.ISO"

# New-VM $VMName
New-VHD -Path "$($HostDriveLetter):\Hyper-V\Virtual Hard Disks\$($VMName)_D0-$($VHDSize).VHDX" -Dynamic -SizeBytes $VHDSize
New-VM -Name $VMName -Generation 2 -Memory 4GB –SwitchName "vSwitch"
Set-VMProcessor $VMName -Count 2
Add-VMHardDiskDrive -VMName $VMName -Path "$($HostDriveLetter):\Hyper-V\Virtual Hard Disks\$($VMName)_D0-$($VHDSize).VHDX"
Add-VMDvdDrive -VMName $VMName -ControllerNumber 0 -ControllerLocation 63
Set-VMDvdDrive -VMName $VMName –Path "$($ISOPath)"
Set-VM –Name $VMName –AutomaticStartAction Start -AutomaticStartDelay 30 -AutomaticStopAction ShutDown

# Assign a VLAN
Set-VMNetworkAdapterVlan –VMName $VMName –Access –VlanId 50

# Make the newly created VM HA
Add-ClusterVirtualMachineRole -VirtualMachine $VMName