Hyper-V: create a virtual machine in PowerShell


Windows Server 2019

In this tutorial, I will walk you through how to create a virtual machine on Hyper-V with PowerShell.

The PowerShell commands of the tutorial, we were executed directly on the Hypervisor in a console launched in Administrator mode.

Prerequisite: retrieve the name of the VMSwitch

The first step will be to retrieve the name of the VMSwitch, to do so enter the command below:

Get-VMSwitch

For the rest of the tutorial, we will use the VMSwitch LAB_RDR

Now you have to create the virtual machine with the cmdlet New-VM.

In this tutorial, we are going to create a Generation 2 virtual machine with 2CPU, 4GB of Ram, a 30GB RD virtual hard drive, and network boot.

Unfortunately, you can’t do this with a single PowerShell command.

Creating the virtual machine with New-VM

We must start by creating the virtual machine, here is the command:

It is not possible to specify the number of processors when creating the virtual machine as with the wizard

If the creation of the virtual machine with the PowerShell cmdlet goes well, the result of the command returns the state of the VM.

Computer creation analysis

On the screenshot below, we can see that the virtual machine is in the C: \ VM folder indicated by the -Path parameter and that the virtual hard disk has been created the location indicated by the -NewVHDPath parameter.

From the Hyper-V Manager console, we can find the VM-TEST virtual machine and we can see in the summary that it is indeed generation 2.

Below the properties of the virtual machine, we can see that it is configured to start the network, that the network card is connected to the VMSwitch LAB_RDR and that it has 4GB of RAM. We also see on the captures, that the number of processors is at 1.

Change the number of processors

It is now necessary to change the number of processors to 2 to have the configuration of the virtual machine given as an example. To do this, you have to use the cmdlet Set-VM, which allows you to modify the parameters of a virtual machine.

Enter the following command to adjust the number of processors:

The command did not return.

By returning to the parameters of the virtual machine, we can see that it now has 2 processors.

In brief

1. We get the name of the VMswitch (optional if we know the name):

Get-VMSwitch

2. Creating the virtual machine with New-VM

3. Adjustment of parameters with SET-VM for what is not possible at creation

Conclusion

As you can see, the creation of virtual machine on Hyper-V in PowerShell is not particularly faster than by a graphical interface.

In addition, in the example, there is only one virtual hard disk, to add several, you have to use another command.

PowerShell cmdlets are mainly used when you want to create VM creation scripts to automate actions or batch creation.

IF you want to easily manage your virtual machines on Hyper-V, I advise you to use the admin center.




Leave a Comment