Hyper-V and PowerShell: The Basics

Because it is important with maintaining Virtual Machine environments to be able to repeat routine tasks completely accurately, Windows PowerShell has grown in importance for the job. Now you can manage the Hyper-V environment via PowerShell without needing to use the Hyper-V Manager console. It opens up many opportunities for automation.

The series so far:

  1. Hyper-V and PowerShell: The Basics
  2. Hyper-V and PowerShell: Shielded Virtual Machines

Introduction

Hyper-V is Microsoft’s hypervisor that lets you run multiple virtual machines on a single physical host. Microsoft introduced Hyper-V in Windows Server 2008. Today, there are several ways to manage Hyper-V hosts:

  • Hyper-V manager: This is the default tool used to manage Hyper-V. This tool also manages remote hosts. It allows you to manage virtual machines, but also the network configuration and all Hyper-V settings.
  • System Center Virtual Machine Manager: This tool is part of the Microsoft System Center products. VMM centrally manages one or more Hyper-V hosts. It provides advanced Hyper-V administration and you can also manage VMware hosts by integrating your VMware vCenter.
  • Windows PowerShell: To simplify the management, it is possible to use the Hyper-V PowerShell module to configure and work with your virtual machines. With PowerShell, you can accomplish most of the tasks that you can accomplish with the GUI.

PowerShell and Hyper-V

Why use PowerShell to manage Hyper-V? Of course, you can use the GUI to perform most of the actions that we will describe in this article. However, PowerShell has several advantages. It allows you to automate the tasks and gives you more flexibility. In some cases, you have no option to using PowerShell because Microsoft does not automatically include all the features of Hyper-V in the GUI.

The first step is to install Hyper-V on your Windows machine. Remember that it is possible to install Hyper-V not just on a Windows server, but also on Windows 10. Use this command to install it on Windows Server:

Make sure that you include the -IncludeManagementTools parameter. This will install the Hyper-V Manager console and the Windows PowerShell module for Hyper-V.

Use this command to activate the role on Windows 10:

By Installing Hyper-V on Windows 10, you can use your own machine to test, and become familiar with, Hyper-V without any additional cost. All you need is a Windows machine with enough memory and processor to work comfortably.

Now you can use the Get-Command cmdlet to check if the PowerShell Hyper-V module is available:

To make it easier to search for commands, pipe the output to the Out-GridView cmdlet. It also pays to update the help files before you begin with Hyper-V and PowerShell.

Ok, let’s explore how you can automate many of your Hyper-V maintenance tasks with PowerShell.

Configuring Hyper-V Host

Although you have installed Hyper-V on your machine, it is not yet completely configured and adapted to your environment. Firstly, let us see the characteristics of our Host with the Get-VMHost cmdlet, not to be confused with Get-VM cmdlet which displays the VMs that are running on the host. I will come back to the latter command in the next section:

Most cmdlets do not display all the available properties. To change this, we must add the Select-Object cmdlet and then add the wildcard *.

What are these properties?

  • The name of the server (In my case it is my Windows 10 laptop),
  • The number of logical processors it has,
  • The amount of memory,
  • And finally, whether the live migration is enabled.

This cmdlet accepts the -ComputerName parameter to query a remote host.

Note that the virtual switches are not included in the previous result. To display them, you must use the Get-VMSwitch cmdlet. You will find that this command returns no result, which is normal.

The communication between the Hyper-V host and its VMs is based on the concept of the VMSwitch. Here is a very simple diagram:

Figure 1 – Hyper-V Virtual Switch

When a VMSwitch is linked to a Physical Network Adapter, then VMs will use this VMSwitch to be connected to the network; so we must identify which one will be used via the Get-NetAdapter cmdlet:

In the example, the adapter is called “Ethernet”. You can use the New-VMSwitch cmdlet to create a new virtual switch using Windows PowerShell. In my case, the following command is used to create a VMSwitch named “My Virtual Switch” that is assigned to the physical network adapter named “Ethernet”:

For help with the syntax of this cmdlet, use the Get-Help New-VMSwitch command.

Creating VMs

We have configured the essentials for using our host. Here’s how to deploy a virtual machine. The first thing is to list the virtual machines already running on the host. For this, use the Get-VM cmdlet, which does exactly what its name implies:

This PowerShell cmdlet returns an object, so if you need more information about a VM, add the -Name parameter and you can pipe the previous cmdlets output to the Format-List cmdlet:

You then get a set of very interesting properties. The output was truncated but here are some examples of the most commonly used properties:

  • IntegrationServicesState: Allows you to verify whether the Integration Services are installed. For those using VMware, this is the equivalent of VMware Tools.
  • Generation: Displays the version of the virtual machine (1 or 2)
  • State / Status / OperationalStatus: Several properties allow to precisely verify the health of the virtual machine.
  • Uptime: Execution time of the VM
  • MemoryAssigned: Memory assigned to the virtual machine
  • Path: Where the *.VHDX files are located
  • ProcessorCount: The number of processors assigned to the virtual machine

For PowerShell One-Liners, you can easily get these properties for all your VMs:

Let us now see the next administration task that you will use: Create your first VM. We use several parameters:

  • Name: corresponds to the name of the VM
  • MemoryStartupBytes: corresponds to the amount of memory allocated
  • SwitchName: corresponds to the VMSwitch name previously created
  • NewVHDPath: corresponds to the location where the VHDX file will be stored (This file corresponds to the VMDK file for VMware)
  • NewVHDSizeBytes: corresponds to the VHDX file size

The machine is created and is stopped. Some actions can only be made after the creation of the VM, such as increasing the number of processors, increasing memory. Here are some basic actions that will be helpful for your daily tasks:

Create a second disk

The file is created, all that remains is to attach it to our VM:

PowerShell does not return us any information. So how to know if the disc is actually attached? Well, simply run the following command:

Increase the number of processors

Increase the memory

To check if previous actions were applied, you can of course use the Hyper-V console:

Figure 2 – VM settings from Hyper-V GUI

Working With VMs

Ok, let us summarize the steps made so far:

  1. Installing the Hyper-V role
  2. Configuring the Network
  3. Creating a VM
  4. Configuring the VM

The next step is to start and shut down our VMs. The following cmdlets are very easy to use, so let us first see an example:

Stopping the machine is done via the Stop-VM cmdlet. This action makes the machine stop through the operating system. For those using VMware, this is equivalent of the “Guest Shutdown” option.

You may get the following error message:

PS > Stop-VM -name VMTest
Stop-VM : The virtual machine is locked. An interactive shutdown cannot proceed while the virtual machine is locked.
At line:1 char:1
+ Stop-VM -name VMTest
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Microsoft.HyperV.PowerShell.ShutdownTask:ShutdownTask) [Stop-VM], Virtual
   izationOperationFailedException
    + FullyQualifiedErrorId :
Unspecified,Microsoft.HyperV.PowerShell.Commands.StopVMCommand

This means that the machine is in use by another process. To work around this, the -force parameter can be used:

Note: the -TurnOff parameter can also be used. This is the equivalent of “PowerOff” via VMware.

More information is available here: https://technet.microsoft.com/fr-fr/library/hh848468.aspx

Let us finish by touching on the Hyper-V ‘checkpoints’ concept. Checkpoints are not considered as backups, but you will still find them to be very useful. Indeed, they are regularly used before performing an action on a VM such as an update, by saving the state of the virtual machine. In this way, it is very easy to roll back to the previous state if the update fails. The official term is “Checkpoint” but cmdlets also uses the term “Snapshot” that is well known to any VMware sysadmin.

To create a checkpoint, select the virtual machine using the Get-VM cmdlet and pipe this to the Checkpoint-VM cmdlet. Use the –SnapshotName parameter to give a name. The complete command looks like the following:

You can easily view the checkpoints with the Get-VMCheckpoint cmdlet and remove them with Remove-VMCheckpoint:

To Go Further

The Hyper-V console is limited because it only allows you to work on a single VM at a time, unlike PowerShell which you can use to interact with multiple machines simultaneously. So, you can easily create scripts to automate tasks. Consider the following example where you want to configure all your VMs with 4 processors:

Another example for creating a Checkpoint on all your VMs at once:

Finally, you will be able to plan an export of your VMS in a regular manner to backup them. Save the following lines in “ExportVM.ps1” file:

All that remains to do is to schedule this script to be triggered at the frequency you need:

Conclusion

We have described the basic cmdlets to manage Hyper-V environment. PowerShell will help you to automate various repetitive tasks such as configuring Hyper-V in either a standalone host or Hyper-V cluster, provisioning a virtual machine or managing Checkpoints.

Each example used in this guide can be applied in bulk mode to automate the management of your environment. If you want to read more about working with Hyper-V using PowerShell, you can start with this article: https://technet.microsoft.com/en-us/library/hh848559.aspx. To learn more about a particular PowerShell command use, Get-Help.

Finally, if you want to go even further in the management and automation of Hyper-V with PowerShell, I advise you to study the new “PowerShell Desired State Configuration” feature. Indeed, DSC provides a resource named xHyper-V that will allow you to completely automate Hyper-V management. For this, I redirect you to the following article about DSC resources: https://www.simple-talk.com/sysadmin/powershell/powershell-desired-state-configuration-dsc-resources/