Configuring virtual machines using PowerShell


In my previous article “Configuring Hyper-V hosts using PowerShell” here in my articles section on we examined some of the Windows PowerShell capabilities built into Windows Server 2012 and Windows Server 2012 R2 that let you perform various configuration tasks for Hyper-V hosts from the PowerShell command line or by running PowerShell scripts. PowerShell can not only be used to manage Hyper-V hosts but also to configure and manage virtual machines running on these hosts. This present article provides a few examples of what you can do in this area. The explanation and procedures included below are adapted from my book Training Guide: “Installing and Configuring Windows Server 2012 R2” (Microsoft Press, 2014). Also included near the end of this article are a few additional tips on this subject that I’ve gleaned from the larger IT pro community including the almost 100,000 followers of our WServerNews weekly newsletter which you can subscribe to at

Creating virtual machines

You can create new virtual machines on a Hyper-V host by using either Hyper-V Manager or Windows PowerShell. You can use the New-VM cmdlet to create a new virtual machine using Windows PowerShell. For example, to create a new virtual machine named SRV-A on HOST4, assign the virtual machine 1 GB of startup memory, attach it to the virtual switch named CONTOSO Virtual Switch, create a new virtual hard disk (VHDX file) of 500 GBs in the default location, and make the virtual CD drive the default boot device, use the following command:

PS C:\> New-VM -ComputerName HOST4 -Name SRV-A -MemoryStartupBytes 1GB `
-BootDevice CD -SwitchName "CONTOSO Virtual Switch" -NewVHDSizeBytes 500GB `
-NewVHDPath SRV-A.vhdx
Name  State CPUUsage(%) MemoryAssigned(M) Uptime   Status
----  ----- ----------- ----------------- ------   ------
SRV-A Off   0           0                 00:00:00 Operating normally

Configuring virtual machines

Once you have created a virtual machine, you might need to further configure its virtual hardware and management settings. You can do this either by opening the virtual machine’s settings in Hyper-V Manager or by using Windows PowerShell. For example, to view the settings of the same virtual machine by using Windows PowerShell, you can use the Get-VM cmdlet as shown here:

PS C:\> Get-VM -Name SRV-A | Format-List *
VMName                      : SRV-A
VMId                        : cabb9f25-1d4a-4ce0-884a-a04520ed0880
Id                          : cabb9f25-1d4a-4ce0-884a-a04520ed0880
Name                        : SRV-A
State                       : Off
OperationalStatus           : {Ok}
PrimaryOperationalStatus    : Ok
SecondaryOperationalStatus  :
StatusDescriptions          : {Operating normally}
PrimaryStatusDescription    : Operating normally
SecondaryStatusDescription  :
Status                      : Operating normally
Heartbeat                   :
ReplicationState            : Disabled
ReplicationHealth           : NotApplicable
ReplicationMode             : None
CPUUsage                    : 0
MemoryAssigned              : 0
MemoryDemand                : 0
MemoryStatus                :
SmartPagingFileInUse        : False
Uptime                      : 00:00:00
IntegrationServicesVersion  :
ResourceMeteringEnabled     : False
ConfigurationLocation       : C:\ProgramData\Microsoft\Windows\Hyper-V
SnapshotFileLocation        : C:\ProgramData\Microsoft\Windows\Hyper-V
AutomaticStartAction        : StartIfRunning
AutomaticStopAction         : Save
AutomaticStartDelay         : 0
SmartPagingFilePath         : C:\ProgramData\Microsoft\Windows\Hyper-V
NumaAligned                 :
NumaNodesCount              : 1
NumaSocketCount             : 1
IsDeleted                   : False
ComputerName                : HOST4
Notes                       :
Path                        : C:\ProgramData\Microsoft\Windows\Hyper-V
CreationTime                : 8/13/2012 8:16:47 AM
IsClustered                 : False
SizeOfSystemFiles           : 28464
ParentSnapshotId            :
ParentSnapshotName          :
MemoryStartup               : 1073741824
DynamicMemoryEnabled        : False
MemoryMinimum               : 536870912
MemoryMaximum               : 1099511627776
ProcessorCount              : 1
RemoteFxAdapter             :
NetworkAdapters             : {Network Adapter}
FibreChannelHostBusAdapters : {}
ComPort1                    : Microsoft.HyperV.PowerShell.VMComPort
ComPort2                    : Microsoft.HyperV.PowerShell.VMComPort
FloppyDrive                 : Microsoft.HyperV.PowerShell.VMFloppyDiskDrive
DVDDrives                   : {DVD Drive on IDE controller number 1 at location 0}
HardDrives                  : {Hard Drive on IDE controller number 0 at location 0}
VMIntegrationService        : {Time Synchronization, Heartbeat, Key-Value Pair Exchange, Shutdown...}

To modify these virtual machine settings, you can use the Set-VM cmdlet and other Hyper-V cmdlets. In the sections that follow, we examine only a few of these different virtual machine settings and how to configure them. For additional information on configuring virtual machine settings, search the TechNet Library for the appropriate topic.

Adding virtual disks

You can use Windows PowerShell to create new virtual disks and add them to your virtual machines. For example, say you want to create and attach a 500 GB dynamically expanding data disk to virtual machine SRV-A on HOST4. You can begin by using the Get-VHD command to display a list of disks attached to SRV-A as follows:

PS C:\> Get-VM -VMName SRV-A | Select-Object VMId | Get-VHD | `
Format-List Path,VhdFormat,VhdType,Size
Path                 : C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\SRV-A.vhdx
VhdFormat            : VHDX
VhdType              : Dynamic
Size                 : 536870912000

The preceding command takes advantage of the pipeline capabilities of Windows PowerShell and works like this:

  1. The command Get-VM –VMName SRV-A returns an object representing virtual machine SRV-A.
  2. The output of the preceding command is then piped into the command Select-Object VMId, which returns an object representing the GUID for SRV-A.
  3. The GUID for SRV-A is then piped into the Get-VHD command to indicate which virtual machine is to be queried for its virtual disks.
  4.  The output of the Get-VHD command is then formatted as a list to display only those properties of interest—namely, the path and file name of the virtual disk file, the format it uses, the disk’s type, and the disk’s size.

Next you can use the New-VHD cmdlet to create the new data disk as follows:

PS C:\> New-VHD -SizeBytes 500GB `
-Path "C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\SRV-A-data.vhdx"
ComputerName      : HOST4
Path              : C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\SRV-A-data.vhdx
VhdFormat         : VHDX
VhdType           : Dynamic
FileSize          : 4194304
Size              : 536870912000

Then you can use the Add-VMHardDiskDrive cmdlet to attach the new data disk to location 1 on IDE controller 0 as follows:

PS C:\> Add-VMHardDiskDrive -VMName SRV-A `
-Path "C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\SRV-A-data.vhdx" `
-ControllerType IDE -ControllerNumber 0 -ControllerLocation 1
You can then use the Get-VHD cmdlet as before to verify the result:
PS C:\> Get-VM -VMName SRV-A | Select-Object VMId | Get-VHD | `
Format-List Path,VhdFormat,VhdType,Size
Path      : C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\SRV-A.vhdx
VhdFormat : VHDX
VhdType   : Dynamic
Size      : 536870912000
Path      : C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\SRV-A-data.vhdx
VhdFormat : VHDX
VhdType   : Dynamic
Size      : 536870912000

Alternatively, you can use the Get-VMHardDiskDrive cmdlet to display all disks connected to the IDE controllers on the virtual machine:

PS C:\> Get-VMHardDiskDrive -VMName SRV-A | `
Format-List ControllerNumber,ControllerLocation,Path
ControllerNumber   : 0
ControllerLocation : 0
Path               : C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\SRV-A.vhdx
ControllerNumber   : 0
ControllerLocation : 1
Path               : C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\SRV-A-data.vhdx

Viewing the IDE 0 Controller page and its subpages in the Settings dialog box for the virtual machine in Hyper-V Manager will confirm that the procedure was successful.

Adding and configuring virtual network adapters

You can also use Windows PowerShell to view, add, remove, and configure virtual network adapters of both the network adapter type and the legacy network adapter type. For example, say you want to add a second virtual network adapter to a virtual machine, connect it to a virtual switch on the host, and enable both DHCP Guard and Router Guard on the adapter. To do this, you can begin by using the Get-VMNetworkAdapter cmdlet to display a list of virtual network adapters installed on the virtual machine:

PS C:\> Get-VMNetworkAdapter -VMName SRV-B
Name            IsManagementOs VMName SwitchName        MacAddress   Status IPAddresses
----            -------------- ------ ----------        ----------   ------ -----------
Network Adapter False          SRV-B  CONTOSO Virtua... 00155D0BE600        {}

Next you can use the Add-VMNetworkAdapter to create the new adapter and connect it to the desired virtual switch:

PS C:\> Add-VMNetworkAdapter -VMName SRV-B -VMNetworkAdapterName "Network Adapter 2" `
-SwitchName "MANAGEMENT Virtual Switch"

You can then use the Get-VMNetworkAdapter again to verify the result:

PS C:\> Get-VMNetworkAdapter -VMName SRV-B
Name              IsManagementOs VMName SwitchName      MacAddress   Status IPAddresses
----              -------------- ------ ----------      ----------   ------ -----------
Network Adapter   False          SRV-B  CONTOSO Virt... 00155D0BE600        {}
Network Adapter 2 False          SRV-B  MANAGEMENT V... 000000000000        {}

You can pipe the output of the preceding command into the Format-List cmdlet to determine whether DHCP Guard and Router Guard are already enabled on the adapter:

PS C:\> Get-VMNetworkAdapter -VMName SRV-B -VMNetworkAdapterName "Network Adapter 2" `
| Format-List DhcpGuard,RouterGuard
DhcpGuard   : Off
RouterGuard : Off

Now use the Set-VMNetworkAdapter to enable both of these features on the adapter:

PS C:\> Set-VMNetworkAdapter -VMName SRV-B -VMNetworkAdapterName "Network Adapter 2" `
-DhcpGuard On -RouterGuard On
Running Get-VMNetworkAdapter again verifies the result:
PS C:\> Get-VMNetworkAdapter -VMName SRV-B -VMNetworkAdapterName "Network Adapter 2" `
| Format-List DhcpGuard,RouterGuard
DhcpGuard   : On
RouterGuard : On

Configuring Dynamic Memory

You can also use the Set-VM cmdlet to enable and configure Dynamic Memory for a virtual machine using Windows PowerShell. For example, say you wanted to enable Dynamic Memory for a virtual machine named SRV-B that is running on HOST4 and configure the maximum RAM as 4 GBs. To do this, you first have to stop the virtual machine because you cannot enable or disable Dynamic Memory while the virtual machine is running. You can use the Stop-VM cmdlet to do this as follows:

PS C:\> Stop-VM -Name SRV-B -ComputerName HOST4

Next you can use the Set-VM cmdlet to enable Dynamic Memory for the virtual machine and set the maximum RAM to 4 GBs as follows:

PS C:\> Set-VM -Name SRV-B -ComputerName HOST4 -DynamicMemory -MemoryMaximumBytes 4GB

Now you can use Start-VM to restart the stopped virtual machine:

PS C:\> Start-VM -Name SRV-B -ComputerName HOST4

Finally, you can use Get-VM to verify the result:

PS C:\> Get-VM -Name SRV-B -ComputerName HOST4 | `
Format-List DynamicMemoryEnabled,MemoryMaximum
DynamicMemoryEnabled : True
MemoryMaximum        : 4294967296

Now say that you decide later that 3 GBs would be a better value for maximum RAM than 4 GBs. By using the –Passthru parameter, which specifies that an object is to be passed through to the pipeline, you can make the change and verify the result by using a single Windows PowerShell command as follows:

PS C:\> Stop-VM -Name SRV-B -ComputerName HOST4 -Passthru | Set-VM -DynamicMemory `
-MemoryMaximumBytes 3GB -Passthru | Start-VM -Passthru | Get-VM | `
Format-List DynamicMemoryEnabled,MemoryMaximum
DynamicMemoryEnabled : True
MemoryMaximum        : 3221225472

For more information on using the –Passthru parameter, see “Use the PowerShell Passthru Parameter and Get Back Objects”.

Configuring bandwidth management

You can also use the Set-VMNetworkAdapter cmdlet to configure bandwidth management settings for a virtual network adapter using Windows PowerShell. The Set-VMNetworkAdapter cmdlet enables you to specify maximum and minimum bandwidth in either megabits per second (Mbps) or in terms of a relative weight between 0 and 100. You can use the latter approach to control how much bandwidth the virtual network adapter can have compared to other virtual network adapters connected to the same virtual switch. For example, you can use the following command to implement bandwidth fair-sharing, in which every virtual network adapter for the specified virtual machines is assigned the same minimum bandwidth weight:

PS C:\> Get-VMNetworkAdapter -VMName SRV-A,SRV-B,SRV-C | Set-VMNetworkAdapter
-MinimumBandwidthWeight 1

You can also configure a minimum bandwidth (either absolute or relative) for a virtual switch by using the Set-VMSwitch cmdlet. You can also do this when you create a new virtual switch using the New-VMSwitch cmdlet. You cannot configure this setting using Hyper-V Manager.

Some Additional Tips

Finally, here are a few more tips on this subject that I’ve gleaned from my colleagues in IT and from readers of our newsletter

Checking status of integration components

When you migrate a virtual machine to a newer version of Windows Server you should also upgrade the integration components on the virtual machine. To check the current status of the integration components for virtual machines on your host, you can use this command:

Get-VM | ft name,integrationservicesversion,integrationservicesstate

Checking status of running virtual machines

If you only want to view the configuration of virtual machines that are currently running on a host, you can use this command:

Get-VM -computername <name> | where-object {$_.State -eq ‘Running’}

Migrating virtual machines between AMD and Intel hosts

Since Hyper-V 2008 R2 you can live migrate virtual machines between Hyper-V hosts that have different processor architectures e.g. AMD vs. Intel. However, before you do that you should make sure that the CompatibilityForMigrationEnabled setting on your virtual machines is set to True. You can do this as follows:

Get-VM | Set-VMProcessor – CompatibilityForMigrationEnabled $True

Additional Resources

For information about the syntax of the Hyper-V cmdlets and for usage examples, see “Hyper-V Cmdlets in Windows PowerShell“.

Leave a Comment

Your email address will not be published.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Scroll to Top