Skip to main content

Build Hyper-V Virtual Machines

In total when I am building the lab environment I start with seven Windows VMs with a mix of sever and client operating systems. While it doesn't take much time to create a VM and make the necessary changes, there is no reason not to automate it if you can, especially since some of the necessary changes are not available in the creation wizard and have to be modified in the properties after creation.

Manually, I would open Hyper-V Manager and create a new VM. The wizard allows you to specify the Name, Location, Generation, Memory allocation, Virtual Switch, Virtual Hard Disk (VHD) name/size/location, and ISO used for installation. In order to complete the configuration, you the need to go into the properties of the VM and adjust the number of processors allocated and adjust the network adapter to use the VLAN used on my lab's subnet. For the few Linux VM's, secure boot also often needs to be disabled.

PowerShell allows all of these to be set within one script with updating a few variables or importing all of the details from a .csv file. I just update the variables and run and it takes care of all of the manual configuration steps.

$VMName = 'Name'
$Memory = 8GB
$BootDevice = 'VHD'
$VHDPath = "C:\$VMName\Virtual Hard Disks\$VMName.vhdx"
$Path = "C:\"
$NewVHDSize = 50GB
$ISO = "Path to ISO"
$VLAN = 'VLAN ID'

New-VM -Name $VMName -MemoryStartupBytes $Memory -BootDevice $BootDevice -NewVHDPath $VHDPath -Path $Path -NewVHDSizeBytes $NewVHDSize -Generation 2 -Switch External
$DVD = Add-VMDvdDrive -VMName $VMName -Path $ISO -Passthru
Set-VMFirmware -VM (Get-VM -Name $VMName) -FirstBootDevice $DVD
Set-VMNetworkAdapterVlan -VMName $VMName -Access -VlanId $VLAN
Start-VM -Name $VMName
vmconnect.exe {HV Host} $VMName