Categories
PowerShell Windows

How to create a Hyper-V VM via PowerShell

To create a VM in Hyper-V (or any hypervisor for that matter) we need to define a few necessary virtualized hardware components. We need to define memory (RAM), CPU(s), and a boot device. For our purposes we will use a Virtual Hard Disk as our boot and storage device.

Let’s start!

Open an elevated Windows PowerShell prompt or Powershell ISE (Run as Administrator)

Elevated PowerShell prompt

Now, we are going to create Virtual Hard Disk (VHD) using the following command. (name of the VHD, storage path, and capacity are up to you.)

New-VHD -Path "C:\VHD_TEST\VirtualHardDisk.vhdx" 60GB

Let’s define a VM…the following command creates a new Gen2 VM with 2GB of memory. In this example, I have given it a descriptive name of “Andre’s CentOS VM”

New-VM -Name "Andre's CentOS VM" -Path "C:\VM" -MemoryStartupBytes 2048MB -Generation 2

(optional ) Let’s adjust the number of processors to 2 (default: 1)

Set-VMProcessor -VMName "Andre's CentOS VM" -Count 2

(optional) Disable SecureBoot as we are planning on installing CentOS on this VM in the future.

Set-VMFirmware "Andre's CentOS VM" -EnableSecureBoot Off

(optional) We’re going to add a network adapter and attach it to a virtual switch.

Add-VMNetworkAdapter -VMName "Andre's CentOS VM" -SwitchName "Default Switch"

(optional) Let’s also add a virtual DVD drive for OS installation media.

Add-VMDvdDrive -VMName "Andre's CentOS VM" -Path "C:\ISO\CentOS-7-x86_64-Minimal-1908.iso"

Alternatively, we could create a VM with a single command using the following:

New-VM -Name "Andre's CentOS VM" -MemoryStartupBytes 2048MB -BootDevice VHD -VHDPath "C:\VHD_TEST\VirtualHardDisk.vhdx" -Path "C:\VM" -Generation 2 -Switch "Default Switch"