Essential PowerShell Cmdlets for Managing Hyper-V

Essential PowerShell Cmdlets for Managing Hyper-V

PowerShell v4 includes 178 Hyper-V related cmdlets. Learn how to create new virtual machines, start, monitor and remove VMs, set up the Virtual Switch for networking, all through PowerShell.

Hyper-V is Microsoft's server virtualization solution that competes with Citrix XenServer, VMware ESXi, and Red Hat Enterprise Virtualization. Windows Server 2012 ships with Hyper-V, which boasts the largest virtual machines currently available and the most flexible virtualization platform with features such as Secure Boot, PXE boot, Live Export, and UEFI firmware support. This article explores Hyper-V via PowerShell version 4.0 on Windows Server 2012 R2.

PowerShell 4.0, the latest version of the scripting language, is the most powerful version to date. To get version 4.0, download and install the Windows Management Framework 4.0 package from the Microsoft's Download Center.

Check out: Essential PowerShell Cmdlets for Managing Storage

The system used for this article is Windows Server 2012 R2 running on an HP ProBook 6460b with Intel CPU virtualization enabled. It's equipped with Intel Core i5-2520M CPU @ 2.50GHz and 4GB RAM.

Enable Hyper-V via PowerShell

If the Hyper-V role isn't enabled on your system, you have to do that first. Hyper-V isn't automatically setup on Windows Server 2012. You can enable Hyper-V via PowerShell. To do so, open a PowerShell window as Administrator by right clicking on the PowerShell shortcut in the Taskbar and select 'Run as Administrator.'

You need to be sure that the Hyper-V role isn't already enabled. At the PowerShell prompt, type:

    PS C:\> Get-WindowsFeature

You'll see the entire list of roles and features display down the screen for you. Scroll up until you see the Hyper-V entry as shown in Figure 1.

    Figure 1: Verifying that the Hyper-V role is not enabled.

To enable Hyper-V on your system, enter the following cmdlet; note that this reboots the system after setup is complete. Hyper-V requires a reboot so entering the –Restart switch automatically reboots rather than prompting you for permission to do so.

    PS C:\> Install-WindowsFeature Hyper-V –Restart

A progress bar appears at the top of your screen to notify you of the changes. Your system reboots to finish the setup process. If you have visual access to the system, you'll note the progress indicator on the system's console during the boot process.

Install Hyper-V PowerShell Module

Check your system to see a list of Hyper-V related cmdlets with:

    PS C:\> Get-Command –Module Hyper-V

Your system might return no results to this command. The reason is that though you've installed the Hyper-V role, the Hyper-V PowerShell module didn't install. To install the module, you have to import it separately.

First, load the ServerManager Module:

    PS C:\> Import-Module ServerManager

Respond to the security warning, if presented, by typing 'R' <ENTER> to proceed with loading the ServerManager module.

Then, load the Hyper-V PowerShell Module located in the Remote Server Administration Tools feature.

    PS C:\> Add-WindowsFeature RSAT-Hyper-V-Tools –IncludeAllSubFeature

After a few minutes you'll receive the system response that the installation was successful and that no restart (reboot) is needed. 
   Figure 2: Importing the ServerManager and Hyper-V Modules.

Note: If you ever have problems executing a script or cmdlet, especially a third-party one, enter the following cmdlet.

    PS C:\> Set-ExecutionPolicy Unrestricted

Type 'Y' when prompted to accept the conditions. Check to see that your Hyper-V cmdlets have been imported.

    PS C:\> Get-Command –Module Hyper-V

A list of 178 new cmdlets has been added to your PowerShell library. After loading the Hyper-V module, or any new module, you have to update your help files so that you have complete online help for the new cmdlets.

    PS C:\> Update-Help 

After a few minutes, your new help files will be downloaded and available.

Preparing to Create a New Virtual Machine

There are a few things you need to know before creating your first VM:

  • The VM name,
  • The network connection type,
  • How you will install the operating system.

For the name, use a standard, descriptive naming convention. Don't worry about spaces or name length because this name only identifies the VM; it isn't the system name. You will need to know if your system requires Internet access or will only use internal (host only or isolated network) connectivity. Finally, you need to know whether you're using physical media, an ISO to install the operating system, or an existing virtual hard disk with a pre-installed operating system.

Creating a New Virtual Machine

Working with virtual machines (VMs) at the command line might seem off-putting at first, but for automation and quick provisioning, you'll find that the PowerShell command line interface (CLI) is very efficient. You can always check the graphical Hyper-V Manager to verify your work, but after you become familiar with working in the CLI, you won't need the visual confirmation.

The following cmdlet creates a new VM with the filesystem name, "Ubuntu 10.04" with 512MB RAM, and a new 10GB virtual hard disk in C:\VM.

    PS C:\> New-VM –Name “Ubuntu 10.04” –MemoryStartupBytes 512MB –NewVHDPath
    C:\VM\ubuntu1004.vhdx –NewVHDSizeBytes 10GB            

Figure 3 below shows you the response from the system once the VM has been created.   Figure 3: Creating a new VM.

The virtual hard disk created is a dynamically sized one, which means that the disk file will grow as you install an operating system and software. The initial size of the disk file (ubuntu1004.vhdx) is 4MB.

If you prefer to use a fixed size disk for your virtual machine(s), you have to create the virtual disk first and then refer to it during the creation of your virtual machine.

   PS C:\> New-VHD –Path C:VMDisk2.vhdx –Fixed –SizeBytes 10GB

A progress indicator gives you feedback on the creation of the new disk. The system then displays a summary of the disk you created as shown in Figure 4.
   Figure 4: Creating a fixed size disk for a virtual machine.

Create the new VM and refer to the previously created disk.

    New-VM –Name “Ubuntu Server 2” –MemoryStartupBytes 512MB –VHDPath C:VMDisk2.vhdx

See Figure 5 for the virtual machine creation details.
   Figure 5: Creating a new VM with a fixed size disk.

Figure 6 is a screenshot of the host's VM folder showing both disks.
   Figure 6: Displaying virtual hard disks - fixed size and dynamic size.

Note: The C:VM folder didn't exist prior to this exercise nor do the commands create it. I created it manually on the filesystem. 

Starting and Monitoring a Virtual Machine

You can start (power on) a virtual machine with the Start-VM cmdlet and identifying the VM that you want to start.

    PS C:\> Start-VM –Name “Ubuntu Server 2”

You'll receive no response to the Start-VM cmdlet unless something goes wrong. To see the status of your VM, use the Get-VM cmdlet.

    PS C:\> Get-VM –Name “Ubuntu Server 2”

See Figure 7 for details.    Figure 7: Checking the status of a virtual machine.

The VM status is 'Running.' You might realize that there's no operating system installed on the virtual disk specified in the VM creation cmdlet you issued, nor have you pointed to any physical media or to an ISO file for booting. A quick check of the graphical Hyper-V Manager reveals that the VM is stuck at a boot failure screen. See Figure 8.
   Figure 8: Booting a VM without bootable media.

To remedy this situation, you must supply bootable media to the VM and restart the boot process. To do this, you use the Add-VMDrivecmdlet.

    PS C:\> Add-VMDvdDrive -VMName “Ubuntu Server 2” –Path C:ISOubuntu-10.04.4-server-i386.iso

If you try this with the VM powered on, you will receive the error 'failed to add device.'

Power off the VM.

    PS C:\> Stop-VM –Name “Ubuntu Server 2”

Press the ENTER key to confirm.

Issue the Add-VMDvdDrivecmdlet again, then start the VM to boot to the ISO image. See Figure 9
   Figure 9: Pointing the VM to a bootable ISO image.

The VM boots to the ISO image and begins the operating system installation process. To install the operating system interactively, you will have to use the graphical Hyper-V Manager application.

During operating system installation, you will receive a warning that no network interfaces have been found, as shown in Figure 10.
    Figure 10: Installing the operating system from bootable media and receiving network interface warning.

You can continue to install the VM and setup networking after you finish or you can choose to stop the VM, setup networking, and then continue the process. In either case, the process of setting up a virtual switch is the same. For my own installation, I'm going to go back in the installation process prior to the point where Ubuntu Linux detects network hardware.

Setting Up the Virtual Switch for Networking

To setup a virtual switch, you have to know the name of your adapter. The name is the "friendly" name that's used for the adapter. It's not the brand or the device name, such as Intel Centrino Advanced-N 6205 or /dev/eth0, but instead a name such as PROD, MGMT, or Adapter #1. In many cases, you have given it the friendly name during configuration.

To find the friendly name, use the following PowerShell cmdlet:

   PS C:\> Get-NetAdapter

     Figure 11: Displaying the name of the host system's network adapters.

The name of my adapter is Wi-Fi. That's the name I'll use to define a virtual switch on my host system.

    PS C:\> New-VMSwitch –Name “VMNetwork” –NetAdapterName “Wi-Fi”

After a minute or two, your system responds with the new virtual switch configuration, as shown in Figure 12.
    Figure 12: Creating a new virtual switch on the host system.

Note that the switch type is External. This means that VMs using this switch will have access to the same external network that the bound adapter does. If you want to create a private or internal switch, you must specify Internal or Private.

For example, if you wanted the switch above to be private, use the SwitchType parameter with the Private option. Do not specify a bound adapter. If you specify an adapter to bind the switch to, the assumption is that you want external connectivity.

    PS C:\> New-VMSwitch –Name “VMNetwork” –SwitchType Private

Add a network adapter (Virtual NIC) to your VM. Remember to power off your VM before you add hardware to it.

    PS C:\> Stop-VM –Name “Ubuntu Server 2”

Reply 'Y' to the verification prompt.

    PS C:\> Add-VMNetworkAdapter –VMName “Ubuntu Server 2” –Name “NIC0”

You'll receive no response from the system.

Now that you've created a virtual switch, it's time to connect your VM's NIC to that switch.

PS C:\> Connect-VMNetworkAdapter-VMName“Ubuntu Server 2” -Name “NIC0” -SwitchName“VMNetwork”

If everything goes well, you'll see no response from the system. Because you're not used to the CLI, enter the following cmdlet to see that your VM is now configured to connect to the virtual switch you created.

PS C:\> Get-VMNetworkAdapter –VMName “Ubuntu Server 2”

Figure 13: Verifying the VM is associated with the virtual switch. Start your VM and continue with your operating system installation.

    PS C:\> Start-VM –Name “Ubuntu Server 2”

If you find that your network adapter still isn't found or doesn't work, then you should try removing the virtual network adapter and replacing it with the legacy network adapter. This works in older Linux distributions, such as Ubuntu 10.04 used in this example. Remember that to remove or add hardware to your VM, you have to first power it down with the Stop-VM cmdlet.

PS C:\> Stop-VM –Name “Ubuntu Server 2”

PS C:\> Remove-VMNetworkAdapter -VMName “Ubuntu Server 2” -VMNetworkAdapterName “NIC0”

Verify the removal, if prompted.

Replace the adapter with the legacy version with the following cmdlet.

PS C:\> Add-VMNetworkAdapter –VMName “Ubuntu Server 2” –Name “NIC0” –IsLegacy 1

Reconnect the legacy NIC to the VMNetwork virtual switch.

PS C:\> Connect-VMNetworkAdapter-VMName“Ubuntu Server 2” -Name “NIC0” -SwitchName“VMNetwork”

Start your VM.

    PS C:\> Start-VM –Name “Ubuntu Server 2”

Removing a VM

To remove a VM from your host, issue the following cmdlet:

    PS C:\> Remove-VM –Name “Ubuntu 10.04”

Confirm that you want to remove the VM by pressing ENTER at the prompt. If your VM is running, you will receive an error informing you that the VM can't be removed in its current state. Stop the VM and then proceed with removal.      Figure 14: Removing a VM from inventory and confirming its removal.


This brief introduction to PowerShell for Hyper-V management is a good basis on which you can build. As stated earlier, there are 178 Hyper-V related cmdlets ranging from starting and stopping of your virtual machines to very advanced cmdlets that allow you, for example, to compare a VM and a VM host for compatibility (Compare-VM) and to move virtual machines from one Hyper-V host to another (Move-VM).

Unfortunately, PowerShell can't prevent mistakes and they're easy to make. The consequences of shutting down and removing the wrong VM are obvious. Pay close attention to VM names when making changes. The confirmation default is 'Yes' in most cases, which makes it easy to execute a cmdlet by pressing ENTER at the prompt. It's both convenient and dangerous. With great PowerShell comes great responsibility!