Using PowerShell commands for daily tasks

As a virtualization administrator, you will come across a lot of scenarios where you will need to create, modify, move, export, and carry out other tasks to manage your virtual machines every day. In some cases, you will need to change a few small and easy settings, which can be done via a graphical interface. However, you will also get cases where lots of virtual machines will need some advanced configuration or settings that take a long time to complete.

It's a fact that PowerShell is a handy and strong ally in all these examples, and this recipe will show some examples of how to perform daily tasks such as disk, network, memory, export, and virtual-machine manipulation using a couple of small and simple PowerShell commandlets.

Getting ready

Make sure that you have a PowerShell window opened as administrator before you start.

How to do it...

These tasks show lots of handy examples of daily tasks that can be used to help you administer your Hyper-V servers, such as creating and changing VHDs, virtual switches, VM tasks, migrations, and much more:

  1. Let's start with a simple command, New-VHD, to create a virtual hard disk for a VM. Type the following command to create a 20GB Dynamic VHDX file named NewDisk on the D: partition. You can use the parameter -Fixed to create a fixed VHDX:
    New-VHD -SizeBytes 20GB –Path D:NewDisk.vhdx -Dynamic
    
  2. To create backwards-compatible virtual machines directly on Windows 10 and Windows Server 2016 using PowerShell, you need to use New-VM with -Version parameter:
    New-VM -Name NewVM -Version 5.0
    

    Version 5.0 means that the VM is completely compatible with Windows Server 2012 R2 / Windows 8.1.

  3. To return a list of virtual-machine configuration versions that are supported on a Hyper-V host, you can use the Get-VMHostSupportedVersion command, as shown in the following screenshot.
    How to do it...
  4. To add the created VHDX file to a VM, use the command Add-VMHardDiskDrive, as shown here:
    Add-VMHardDiskDrive -VMName NewVM -Path D:Hyper-VNewDisk.vhdx
    
  5. To create a new virtual switch, you can use the New-VMSwitch command. The following example creates an external switch and binds it to a network adapter called Ethernet:
    New-VMSwitch "Ext_vSwitch" –NetAdapterName "Ethernet" –AllowManagementOS $false
    
  6. To add a network adapter to a VM, use the Add-VMNetworkAdapter command. The following command adds a network adapter named Prod NIC to all the virtual machines that start with Prod:
    Add-VMNetworkAdapter -VMName Prod* -Name "Prod NIC"
    
  7. To rename a network adapter to a VM, use the Rename-VMNetworkAdapter command. The following command renames the default, "Network adapter", to "Prod NIC" for a specific VM:
    Rename-VMNetworkAdapter -VMName New-VM -Name "Network Adapter" -NewName "Prod NIC"
    
  8. Use the Connect-VMNetworkAdapter to add VMs to a virtual switch. The following command gets all the VMs, starting with TestVM, and adds them to a switch called Private Switch:
    Connect-VMNetworkAdapter -VMName TestVM* -SwitchName 'Private Switch'
    
  9. To add a legacy network adapter to a generation-1 virtual machine, you can also use the Add-VMNetworkAdapter with the IsLegacy switch. The following example shows the usage of this command. This gets all the VMs, starting with NewVM, and adds a legacy network named BootableNIC:
    Get-VM NewVM* | Add-VMNetworkAdapter -IsLegacy $true -Name BootableNIC
    
  10. You can use the Set-VMNetworkAdapter to change the virtual machine network-adapter settings. The first command changes the maximum and minimum bandwidth configuration of all virtual machines, starting with VMTest:
    Set-VMNetworkAdapter -VMName VMTest* -MaximumBandwidth 100MB -MinimumBandwidthAbsolute 20MB
    

    The second command enables Mac address spoofing to all VMs that end with NLB:

    Set-VMNetworkAdapter -VMName *NLB -MacAddressSpoofing On
    

    The third command enables device naming to all Generation-2 VMs. The virtual network adapter identification or device naming is a very interesting feature introduced in Windows Server 2016:

    Get-VM * | Where-Object {$_.Generation -eq "2"} | Set-VMNetworkAdapter -DeviceNaming On
    

    Please note that device naming can be enabled using PowerShell, as shown in the previous command, or it can also be enabled using Hyper-V Manager under VM Settings | Advanced Features. Then, inside the virtual machine, you can actually go under Advanced settings for a particular NIC and look at the Hyper-V Network Adapter Name to identify the NIC name you specified, as shown in the following screenshot. This feature is very convenient and useful:

    How to do it...
  11. To add Fibre Channel HBAs to virtual machines, you can use the Add-VMFibreChannelHBA as the next example:
    Add-VMFibreChannelHba -VMName NewVM -SanName VMProd
    
  12. You can also use basic tasks such as starting and stopping virtual machines using the Start-VM and Stop-VM commands, as shown in the following two examples:
    Start-VM -Name SPVM*
    Stop-VM -Name TestVM -TurnOff
    
  13. To lock the VM Console when you close VM Connect in the Hyper-V UI, you can use Set-VM, including the -LockOnDisconnect parameter:
    Set-VM -Name NewVM -LockOnDisconnect On
    

    Please note that, each time you turn On or Off, the VM needs to be rebooted for this to take effect.

  14. To wait for a virtual machine to meet specified criteria before returning, you can use the Wait-VM command with For, Delay, and Timeout parameters:
    Wait-VM -Name NewVM -For IPAddress
    

    The -For parameter Specifies a condition to wait for. Possible values are Heartbeat or IP Address

    The -Delay parameter Specifies a duration in seconds to wait between polling

    The -Timeout parameter Specifies a duration after which the operation will time out and stop waiting

    This is very handy when you are writing scripts and you need to wait until the VM responds. This command leverages the virtual machine Integration Services.

  15. To create a virtual machine checkpoint (aka snapshot), you can use the Checkpoint-VM command. The following example creates a checkpoint called PreMigrationSnapshot to all the VMs starting with ProdServer:
    Checkpoint-VM -Name ProdServer* -SnapshotName PreMigrationSnapshot
    
  16. To create a virtual machine from a snapshot you can use the Export-VMSnapshot command as follows:
    Export-VMSnapshot -Name 'PosUpdates' -VMName NewVM -Path E:NewVMfromSnapshot
    
  17. In the case of a server migration, you can use the Export-VM command to export VMs to a local folder. The following command shows a handy example of all the virtual machines being exported to a local drive in their own folders:
    Get-VM | Export-VM -Path E:ExportedVMs
    
  18. To move the virtual-machine storage, use the Move-VMStorage command, specifying the destination path that you want to move the VM storage to, as shown in the following example:
    Move-VMStorage NewVM -DestinationStoragePath D:NewVM
    
  19. Use the following example to move all the storage for all VMs to a new volume, by creating a folder for each migrated VM:
    Get-VM | %{ Move-VMStorage $_.Name "D:Hyper-V$($_.Name)" }
    
  20. Use Set-VM to change the VM settings. In the following example, all servers starting with VMExchange are having their dynamic memory enabled with the minimum, maximum, and startup values being configured. There's also a command which only changes the memory settings, called Set-VMMemory. The second example does exactly the same thing as the first one, just using different commands:
    Set-VM -Name VMExchange* -DynamicMemory -MemoryMinimumBytes 8GB -MemoryMaximumBytes 12GB -MemoryStartupBytes 10GB
    
    Set-VMMemory -VMName VMExchange* -DynamicMemoryEnabled $true -MaximumBytes 12GB -MinimumBytes 8GB -StartupBytes 10GB
    
  21. You can use the Set-VMHardDiskDrive to change the virtual machine virtual hard disk settings. The first command below is capping the maximum storage quality of service (QoS) for 1,000 input/output operations per second (IOPS) to all virtual hard disks for virtual machines starting with VMTest. The second command is to set the maximum and minimum IOPs on all virtual hard disks attached to SCSI controllers for virtual machines starting with VMTest:
    Get-VMHardDiskDrive -VMName VMTest* | Set-VMHardDiskDrive -MaximumIOPS 1000 
    
    Get-VMHardDiskDrive -VMName VMTest* -ControllerType SCSI |
    Set-VMHardDiskDrive -MaximumIOPS 100 -MinimumIOPS 2
    

    Note

    Note: The minimum IOPs is a soft reserve (best effort), which means it might fail but an event will be logged that things are going wrong. Please check Chapter 3, Managing Disk and Network Settings, and the new storage quality of service introduced in Windows Server 2016 in Chapter 7, Configuring High Availability in Hyper-V.

How it works...

From simple tasks, such as starting a VM, to advanced ones, such as moving all virtual-machine storage to a new location, it is much easier to use PowerShell rather than the GUI interface. From the 232 Hyper-V commandlets, you have seen examples of the following types:

  • Add-VMFibreChannelHba
  • Add-VMHardDiskDrive
  • Add-VMNetworkAdapter
  • New-VMSwitch
  • Connect-VMNetworkAdapter
  • New-VHD
  • New-VM
  • Checkpoint-VM
  • Export-VMSnapshot
  • Move-VMStorage
  • Set-VM
  • Set-VMMemory
  • Set-VMNetworkAdapter
  • Rename-VMNetworkAdapter
  • Start-VM
  • Stop-VM
  • Wait-VM
  • Get-VMHostSupportedVersion

These are the normal commands used day-to-day in order to create disks and networks, change VM settings, start VMs, add fiber-channel adapters, create checkpoints, migrate VMs, and other tasks that can be easily done via PowerShell.

You might encounter other tasks that will require different commands, but with this start, you can have an idea of commands and the things you can do via PowerShell.

This link, https://technet.microsoft.com/library/hh848559.aspx, is a reference that provides cmdlet descriptions and syntax for all Hyper-V specific cmdlets in Server 2016. It lists the cmdlets in alphabetical order based on the verb at the beginning of the cmdlet.

There's more...

If you are not sure whether a commandlet will work or what the result will be, you can test it before you run it. The Whatif switch, added at the end of the PowerShell command, can tell you whether it's going to work or not.

The following screenshot shows a command that uses the w=Whatif option and, when executed, PowerShell explains that it will not work and why. After fixing it, you can try using the Whatif command again. For the Export-VM command, you will see the What if: Export-VM will export the virtual machine "NewVM01" message:

There's more...

Using PowerShell ISE for advanced script editing

For advanced and big scripts, you can use a very interesting built-in tool named PowerShell ISE. It offers a GUI PowerShell window with colors, line count, command predict, error verification, and a debugging option, making your scripting experience easier and faster.

The following screenshot shows an example of a script being written by PowerShell ISE with a window showing the command-prediction feature, and the command column in the pane on the right-hand side:

Using PowerShell ISE for advanced script editing

Enabling scripts to be executed in PowerShell

By default, the scripts execution is disabled in PowerShell for security reasons. However, there is a commandlet to enable or change the default settings. This commandlet is called Set-ExecutionPolicy. This command can change the script execution policy to unrestricted for running every script – remote signed to run remote, signed scripts, or all signed to run only signed scripts – and other options. To change the policy, run the Set-ExecutionPolicy command with the policy that you want to add. In the following example, the command being used enables all the scripts to be executed by changing the policy to unrestricted. You can also use RemoteSigned, AllSigned, Restricted, and other options as the policy:

Set-ExecutionPolicy Unrestricted

After running this command, you will have changed the script execution policy to unrestricted and all the scripts will run without any limitation.

See also

  • The Creating and adding virtual hard disks and Creating and managing virtual switches recipes in Chapter 3, Managing Disk and Network Settings
  • The Enabling and working with remote connection and administration through PowerShell recipe in this chapter
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.79.59