Build a VM

ℹ️
Thank you to Perry MacDonald for contributing to this article.

In this article we’ll walk through the steps to create a Generation 2 Hyper-V virtual machine (VM) via PowerShell.

Create Virtual Hard-Drives

To get started, open a PowerShell prompt (as Administrator) and create the virtual hard-drive.

ℹ️
When specifying the location of the hard-drives its recommended that the location match that of Hyper-V’s default storage location.
New-VHD -Path 'D:\Hyper-V\Virtual Hard Disks\OSDISK.vhdx' -SizeBytes 20GB

Repeat this command as necessary to create multiple virtual hard-drives if desired.

Create Virtual Machine (VM)

Next, we’ll create the virtual machine, attaching one of the VHDs you created in the previous step (usually the OS partition to start).

In this example will create a Generation 2 VM with 2x vCPU, 4GB of memory and attach the VHD located at D:\Hyper-V\Virtual Hard Disks\OSDISK.vhdx.

# Create the virtual machine.
New-VM VMNAME -Generation 2 -MemoryStartupBytes 4GB -VHDPath 'D:\Hyper-V\Virtual Hard Disks\OSDISK.vhdx'

# By default the virtual machine will be assigned one vCPU. This command increases the vCPU count to two.
Set-VMProcessor -VMName VMNAME -Count 2

Attach Additional VHDs

Add any remaining VHDs you created in the first step to the VM.

Add-VMHardDiskDrive -VMName VMNAME -Path 'D:\Hyper-V\Virtual Hard Disks\SECONDDISK.vhdx'

Secure Boot

ℹ️
Secure boot is a security standard developed by members of the PC industry to help make sure that a device boots using only software that is trusted by the Original Equipment Manufacturer (OEM).

By default, Secure Boot is enabled on the VM and configured to work with Windows-based operating systems. If installing a Window’s based operating system, this setting is correct and does not need to be modified. If installing Linux, use the following command to switch to using the UEFI Certificate Authority.

Set-VMFirmware -VMName VMNAME -SecureBootTemplate "MicrosoftUEFICertificateAuthority"

If needed, you can also disable Secure Boot entirely:

Set-VMFirmware -VMName VMNAME -EnableSecureBoot Off

Configure Network

We can now configure how the VM will connect to the network. The following series of command will rename the default network interface from Network Adapter to eth0, connect the VM to a vSwitch called Internal vSwitch and set the VM to communicate on VLAN 100.

# Rename the NIC (optional)
Rename-VMNetworkAdapter -VMName VMNAME -Name 'Network Adapter' -NewName eth0

# connect the virtual machine to the 'Internal vSwitch' vSwitch
Connect-VMNetworkAdapter -VMName VMNAME -Name 'eth0' -SwitchName 'Internal vSwitch'

# tag all traffic from the VM to VLAN 100 (optional)
Set-VMNetworkAdapterVlan -VMName VMNAME -VMNetworkAdapterName eth0 -VlanId 100 -Access

Start VM

With the configuration completed, we can now start the VM.

Start-VM -Name VMNAME

If you ever need to shutdown the VM, you can do so with the reverse command.

Stop-VM -Name VMNAME