Create a VM in Hyper-V using Powershell

Introduction

Learn how to create a virtual machine via Windows PowerShell and what options are available to you when you have the virtual machine in Hyper-V Manager

Prerequisites

Ensure you have one of the following : Windows 10, Windows Server 2016, Microsoft Hyper-V Server 2016, Windows Server 2019, Microsoft Hyper-V Server 2019

Instruction

  • Open Powershell ISE from the start menu (Ensure you run as administrator) and type the following to find your available Virtual Switches.  I am going to use one i created earlier called BlackwaterConfig
  • Get-VMSwitch
  • We are now going to use a pre-defined script to create the VM, i have added comments so you understand what each section means. These are the parameters for the main part of the VM creation for reference.

-Name is the name that you provide for the virtual machine that you’re creating

-MemoryStartupBytes is the amount of memory that is available to the virtual machine at start up

-BootDevice is the device that the virtual machine boots to when it starts like the network adapter (NetworkAdapter) or virtual hard disk (VHD)

-VHDPath is the path to the virtual machine disk that you want to use

-Path is the path to store the virtual machine configuration files

-Generation is the virtual machine generation. Use generation 1 for VHD and generation 2 for VHDX

-Switch is the name of the virtual switch that you want the virtual machine to use to connect to other virtual machines or the network. See Create a virtual switch in Hyper-V using Powershell

Script to Create a VM and load the OS ready to install

  • Load your edited script into PowerShell ISE and click enter (or F5) to run the script

# Set VM Name, Switch Name, and Installation Media Path.
$VMName = ‘London’
$Switch = ‘BlackwaterConfig’
$InstallMedia = ‘C:\Software\en_windows_server_2016_x64_dvd_9718492.iso’

# Create New Virtual Machine
New-VM -Name $VMName -MemoryStartupBytes 4GB -Generation 2 -NewVHDPath “C:\BlackwaterConfig\Virtual Machines\$VMName\$VMName.vhdx” -NewVHDSizeBytes 30GB -Path “C:\BlackwaterConfig\Virtual Machines\$VMName” -SwitchName $Switch

# Add DVD Drive to Virtual Machine
Add-VMScsiController -VMName $VMName
Add-VMDvdDrive -VMName $VMName -ControllerNumber 1 -ControllerLocation 0 -Path $InstallMedia

# Mount Installation Media
$DVDDrive = Get-VMDvdDrive -VMName $VMName

# Configure Virtual Machine to Boot from DVD
Set-VMFirmware -VMName $VMName -FirstBootDevice $DVDDrive

  • Your VM has been created and the ISO is mounted as a DVD drive so once you first start the VM it will be ready for you to boot from CD/DVD, install and configure your chosen OS.  If you open up Hyper-V Manager you will see that the settings have applied successfully
  • Your next step is to Start the VM and install the OS