Reader small image

You're reading from  Learning PowerCLI - Second Edition

Product typeBook
Published inFeb 2017
Publisher
ISBN-139781786468017
Edition2nd Edition
Right arrow
Author (1)
Robert van den Nieuwendijk
Robert van den Nieuwendijk
author image
Robert van den Nieuwendijk

Robert van den Nieuwendijk is an IT veteran from the Netherlands with over thirty years of experience in Information Technology. He holds a bachelor degree in software engineering. After working a few years as a programmer of air traffic control and vessel traffic management systems, he started his own company Van den Nieuwendijk Informatica in 1988. Since then he has worked as a freelance systems administrator of OpenVMS, Windows Server, Linux, and VMware vSphere systems, for Dutch governmental organizations and cloud providers. During winter he is also a ski and snowboard instructor at an indoor ski school. With his background as a programmer, he always tries to make his job easier by writing programs or scripts to perform repeating tasks. In the past, he used the C programming language, OpenVMS DCL, Visual Basic Script and KiXtart to do this. Now, he uses Microsoft PowerShell and VMware PowerCLI for all of his scripting work. Robert is a frequent contributor and moderator at the VMware VMTN Communities. Since 2012 VMware awarded him the vExpert title for his significant contributions to the community and a willingness to share his expertise with others. He has a blog at http://rvdnieuwendijk.com where he writes mainly about VMware PowerCLI, Microsoft PowerShell, and VMware vSphere. If you want to get in touch with Robert, then you can find him on Twitter. His username is @rvdnieuwendijk. Robert is also the author of Learning PowerCLI, Packt Publishing.
Read more about Robert van den Nieuwendijk

Right arrow

Chapter 5. Managing Virtual Machines with PowerCLI

As a VMware vSphere administrator, you probably spend a lot of your time creating, modifying, or removing virtual machines. In this chapter, you will learn how to manage virtual machines, templates, OS customization specifications, snapshots, VMware Tools, and tags with PowerCLI.

The topics that will be covered in this chapter are as follows:

  • Creating virtual machines

  • Registering virtual machines

  • Using OS customization specifications

  • Importing OVF or OVA packages

  • Starting and stopping virtual machines

  • Modifying the settings of virtual machines

  • Converting virtual machines into templates

  • Moving virtual machines to another folder, host, cluster, resource pool, or datastore

  • Updating VMware Tools

  • Upgrading virtual machine compatibility

  • Using snapshots

  • Running commands in the guest OS

  • Configuring Fault Tolerance

  • Opening the console of virtual machines

  • Removing virtual machines

  • Using tags

Creating virtual machines


There are several ways in which you can create a new virtual machine, such as:

  • Deploying a virtual machine from a template

  • Cloning another virtual machine

  • Using VMware vCenter Converter to convert a physical computer to a virtual machine (P2V)

  • Building a new virtual machine from scratch using traditional methods such as an installation CD-ROM or ISO file to install the operating system

To create a new virtual machine using PowerCLI, you have to use the New-VM cmdlet. The New-VM cmdlet has the following syntax, containing four parameter sets.

The default parameter set is shown in the following command line:

    New-VM [-AdvancedOption <AdvancedOption[]>] [[-VMHost] <VMHost>]
    [-Version <VMVersion>] -Name <String> [-ResourcePool <VIContainer>]
    [-VApp <VApp>] [-Location <Folder>] [-Datastore <StorageResource>]
    [-DiskMB <Int64[]>] [-DiskGB <Decimal[]>] [-DiskPath <String[]>]
...

Registering virtual machines


To register an existing virtual machine to your vCenter inventory, you have to specify the path to a .vmx file. A .vmx file contains the configuration for an existing virtual machine. Here are a few lines from a .vmx file:

.encoding = "UTF-8" 
config.version = "8" 
virtualHW.version = "11" 
vmci0.present = "TRUE" 
displayName = "VM4" 
floppy0.present = "FALSE" 
numvcpus = "1" 
memSize = "256" 

You typically don't modify a .vmx file with an editor, because you might break the connection to the virtual machine.

Note

For more information about modifying a .vmx file, read the VMware Knowledge Base article Tips for editing a .vmx file (1714) (available at https://kb.vmware.com/kb/1714 ).

The following example will register a virtual machine named VM4 on host 192.168.0.134. You have to specify the location of the .vmx file of the virtual machine on the datastore as the value of the New-VM -VMFilePath parameter:

PowerCLI C:\>...

Using OS customization specifications


OS customization specifications are XML files that contain guest operating system settings such as the computer name, network settings, and license settings-for virtual machines. You can use OS customization specifications to modify the configuration of the operating system during the deployment of new virtual machines.

Let's get a list of the names of all the OS customization specifications cmdlets:

PowerCLI C:\> Get-Command -Noun OSCustomization* |
>> Select-Object -Property Name

The output of the preceding command is as follows:

Name
----
Get-OSCustomizationNicMapping
Get-OSCustomizationSpec
New-OSCustomizationNicMapping
New-OSCustomizationSpec
Remove-OSCustomizationNicMapping 
Remove-OSCustomizationSpec
Set-OSCustomizationNicMapping
Set-OSCustomizationSpec

To create an OS customization specification or to clone an existing one, you have to use the New-OSCustomizationSpec cmdlet. This cmdlet has the following syntax. The first parameter set...

Importing OVF or OVA packages


The Open Virtualization Format (OVF) is an open standard for packaging and distributing virtual appliances (vApps). An Open Virtual Appliance (OVA) is an OVF package stored in a single file in the TAR format. VMware and other vendors distribute software in the OVA or OVF format. You can create OVF or OVA packages from vApps and virtual machines using the Export-VApp cmdlet.

An application packaged as an OVF or OVA can be imported to your vSphere inventory using PowerCLI. Before you can import an OVF or OVA package, you will have to configure the properties required by the package, such as the following:

  • Name

  • Port group

  • IP address

Retrieving the required properties

Because the required properties are different for each package, you will have to retrieve them first. The Get-OvfConfiguration cmdlet will retrieve required properties from the OVF or OVA package for you.

The syntax of the Get-OvfConfiguration cmdlet is as follows:

Get-OvfConfiguration [-Ovf] <String>...

Starting and stopping virtual machines


You have created your virtual machine, but it is still powered off. In this section, you will learn how to start, suspend, and stop a virtual machine using PowerCLI.

Starting virtual machines

To start a virtual machine, you can use the Start-VM cmdlet. This cmdlet has the following syntax:

Start-VM [-RunAsync] [-VM] <VirtualMachine[]> [-Server 
    <VIServer[]>] [-WhatIf] [-Confirm] [<CommonParameters>]

The -VM parameter is required to start a virtual machine.

In the first example, we will start the virtual machine VM2 using the following command:

PowerCLI C:\> Start-VM -VM VM2

The output of the preceding command is as follows:

Name                 PowerState Num CPUs MemoryGB
----                 ---------- -------- --------
VM2                  PoweredOn  2        4.000

To start all of your virtual machines that are powered off, you can pipe the output of the Get-VM cmdlet to the Where-Object cmdlet, to filter only those virtual...

Modifying the settings of virtual machines


To modify the settings of a virtual machine, you can use the Set-VM cmdlet. This cmdlet has the following syntax. The first parameter set is the default:

    Set-VM [-VM] <VirtualMachine[]> [-Name <String>] [-Version <VMVersion>]
    [-MemoryMB <Int64>] [-MemoryGB <Decimal>] [-NumCpu <Int32>] 
    [-CoresPerSocket <Int32>] [-GuestId <String>] [-AlternateGuestName 
    <String>] [-OSCustomizationSpec <OSCustomizationSpec>] 
    [-HARestartPriority <HARestartPriority>] [-HAIsolationResponse 
    <HAIsolationResponse>] [-DrsAutomationLevel <DrsAutomationLevel>]
    [-Server <VIServer[]>] [-RunAsync] [-VMSwapFilePolicy 
    <VMSwapfilePolicy>] [-Notes <String>] [-WhatIf] [-Confirm]
    [<CommonParameters>]

The second parameter set is for reverting a virtual machine to a snapshot:

    Set-VM [-VM] <VirtualMachine...

Converting virtual machines into templates


You have already learned how to deploy a virtual machine from a template in the Creating virtual machines from templates section. You will now learn how to create a template. You begin by creating a virtual machine and installing the operating system, application software, and patches you need for all the virtual machines you want to deploy. After you have finished creating your new virtual machine, you have to convert it into a template using the Set-VM cmdlet, which you have already seen in the Modifying the settings of virtual machines section. Let's convert the VM1 virtual machine into a template:

PowerCLI C:\> Get-VM -Name VM1 | Set-VM -ToTemplate -Confirm:$false

The output of the preceding command is as follows:

Name
----
VM1

To confirm that VM1 is now a template, you can use the Get-Template cmdlet to view all the templates:

PowerCLI C:\> Get-Template

The output of the preceding command is as follows:

Name
----
VM1

The Get-Template...

Moving virtual machines to another folder, host, cluster, resource pool, or datastore


To move a virtual machine to another folder, host, cluster, resource pool, or datastore, you can use the Move-VM cmdlet. You can also use the Move-VM cmdlet to migrate a network adapter to a new port group. This cmdlet has the following syntax:

Move-VM [-AdvancedOption <AdvancedOption[]>] [[-Destination]
    <VIContainer>] [-Datastore <StorageResource>] [-DiskStorageFormat
    <VirtualDiskStorageFormat>] [-VMotionPriority <VMotionPriority>]
    [-NetworkAdapter <NetworkAdapter[]>] [-PortGroup 
    <VirtualPortGroupBase[]>] [-RunAsync] [-VM] <VirtualMachine[]>
    [-Server <VIServer[]>] [-WhatIf] [-Confirm] [<CommonParameters>]

The -VM parameter is required.

In the first example, we will move the VM2 virtual machine to ESXi host 192.168.0.134:

PowerCLI C:\> Get-VM -Name VM2 | Move-VM -Destination 192.168.0.134

The output...

Updating VMware Tools


When there is a new version of the vSphere ESXi software, it normally comes with a new version of VMware Tools. There are two methods of updating VMware Tools in a guest operating system:

  • Use the Update-Tools cmdlet

  • Enable the Check and upgrade VMware Tools before each power on checkbox and reboot the virtual machine

In this section, we will discuss both options.

In the following screenshot of the vSphere web client, you will see the VM Options tab in the Edit Settings window for the VM2 virtual machine. The Check and upgrade VMware Tools before each power on checkbox is enabled:

Using the Update-Tools cmdlet

The Update-Tools cmdlet will update VMware Tools in a guest operating system. The syntax of this cmdlet is as follows:

Update-Tools [-NoReboot] [-RunAsync] [[-Guest] <VMGuest[]>] 
    [<CommonParameters>]
Update-Tools [-NoReboot] [-RunAsync] [[-VM] <VirtualMachine[]>]
    [[-Server] <VIServer[]>] [<CommonParameters>]

You can...

Upgrading virtual machine compatibility


To upgrade virtual machine compatibility, you can use the Set-VM cmdlet that you have seen before in the Modifying the settings of virtual machines section. You have to use the -Version parameter and specify the new compatibility version as a parameter value. At the time of writing this book, the only valid versions are v4, v7, v8, v9, v10, and v11.

New features in virtual machines compatible with version 9 or higher can no longer be edited with the vSphere C# client. Some devices may not appear in the devices list, and the settings of some devices may appear as Restricted. You will have to use the vSphere web client or PowerCLI to edit the configuration for these virtual machines.

The following example will upgrade the VM7 virtual machine to compatibility version 11:

PowerCLI C:\ > Get-VM -Name VM7 | `
>>  Set-VM -Version V11 -Confirm:$false
>>

The output of the preceding command is as follows:

Name                 PowerState Num CPUs...

Using snapshots


Snapshots are a point in time to which you can revert a virtual machine and changes made to the virtual machine after creating the snapshot will be discarded. For example, snapshots are useful when you are installing or upgrading software on a virtual machine. If the installation or upgrade goes wrong, you can easily revert to the time the last snapshot was taken to get back to the state before you started the installation or upgrade. If you have verified that the installation or upgrade was successful, you should remove the snapshot, because snapshots use valuable space in your datastores and decrease the performance of your virtual machine.

Note

Snapshots are not backups!

In this section, we will discuss the PowerCLI commands to work with snapshots.

Creating snapshots

To create a new snapshot of a virtual machine, you have to use the New-Snapshot cmdlet. This cmdlet has the following syntax:

New-Snapshot [-VM] <VirtualMachine[]> [-Name] <String> 
    [-Description...

Running commands in the guest OS


To run a command on the guest operating system of a virtual machine, you can use the Invoke-VMScript cmdlet. To use this cmdlet, the virtual machines must be powered on and must have VMware Tools installed. You also need network connectivity to the ESXi server hosting the virtual machine on port 902.

The Invoke-VMScript cmdlet has the following syntax:

Invoke-VMScript [-ScriptText] <String> [-VM] <VirtualMachine[]>
    [-HostCredential <PSCredential>] [-HostUser <String>] 
    [-HostPassword <SecureString>] [-GuestCredential <PSCredential>]
    [-GuestUser <String>] [-GuestPassword <SecureString>] 
    [-ToolsWaitSecs <Int32>] [-ScriptType <ScriptType>] [-RunAsync]
    [-Server <VIServer[]>] [-WhatIf] [-Confirm] [<CommonParameters>] 

The -ScriptText and -VM parameters are required. The value of the -ScriptText parameter is the text of the script you want to run...

Configuring Fault Tolerance


VMware Fault Tolerance is a feature that allows you to run a copy of a virtual machine on another host in the same cluster. The primary virtual machine and the secondary virtual machine are synchronized and run in virtual lockstep with each other. When the primary virtual machine fails, the secondary virtual machine takes its place with the minimum possible interruption of service. Detailed instructions for configuring Fault Tolerance in your vSphere environment can be found on the VMware vSphere 6.5 Documentation Center page at https://pubs.vmware.com/vsphere-65/index.jsp under ESXi and vCenter Server 6.5 Documentation | vSphere Availability | Providing Fault Tolerance for Virtual Machines. In this section, we will discuss how to turn Fault Tolerance on and off in a virtual machine.

Turning Fault Tolerance on

There are no PowerCLI cmdlets to turn Fault Tolerance on or off in a virtual machine, so we have to use the VMware vSphere API. In the following example...

Opening the console of virtual machines


The Open-VMConsoleWindow cmdlet opens the console of a virtual machine in a web browser. It will open the console in the browser configured in the VMConsoleWindowBrowser setting in Set-PowerCLIConfiguration, or in the default browser if the setting is not configured. The browser must be a 32-bit browser. You can open the console in a new window or full screen. This cmdlet uses the VMware Remote Console (VMRC) browser plugin.

The syntax of the Open-VMConsoleWindow cmdlet is as follows:

Open-VMConsoleWindow [-VM] <RemoteConsoleVM[]> [-FullScreen]
    [-UrlOnly] [-Server <VIConnection[]>] [-WhatIf] [-Confirm] 
    [<CommonParameters>]

The -VM parameter is required. The -FullScreen parameter will open the console in full screen mode. The -UrlOnly parameter does not open the console but returns the URL needed to open the console. This URL will stay valid for 30 seconds, after which the screen authentication ticket contained in...

Removing virtual machines


In the lifecycle of a virtual machine, there comes a time when you may want to remove it. This may be because the application running on the virtual machine is not in use anymore, or because the operating system running on the virtual machine is obsolete and you have moved the application to a new server. To remove a virtual machine, you can use the Remove-VM cmdlet, which has the following syntax:

Remove-VM [-DeletePermanently] [-RunAsync] [-VM] <VirtualMachine[]>
    [-Server <VIServer[]>] [-WhatIf] [-Confirm] [<CommonParameters>]

If you use the -DeletePermanently parameter, the virtual machine will be removed from your vSphere inventory and the datastores. If you omit the -DeletePermanently parameter, the virtual machine will only be removed from the vSphere inventory. Because the virtual machine's files remain on the datastores, you can register the virtual machine again.

In the following example, we will use the Remove-VM cmdlet to remove...

Using tags


Tags are labels that you can attach to objects in the vSphere inventory. Every object can have zero, one, or many tags attached. You can use tags to group objects based on anything you want.

For example, you can create a John Doe tag that specifies the owner of a virtual machine is John Doe. Using the John Doe tag, you can easily find all of the virtual machines owned by John Doe.

Tag categories are used to group related tags together. Every tag must belong to a tag category. At the creation of a tag category, you can specify to which object types the tags in this tag category can be attached. You can also specify if only one, or more than one, tag in the tag category can be attached to an object.

Continuing the preceding example, you can create a tag category, Owner, which contains the tags for each owner. You can apply this tag category to the virtual machine objects. If you want your virtual machines to have only one owner, you can specify that only one tag from the Owner tag...

Summary


In this chapter, you learned how to create a virtual machine, use OS customization specifications, import OVF or OVA packages, start and stop virtual machines, modify the settings of virtual machines, and convert virtual machines into templates. We looked at moving virtual machines to another folder, host, cluster, resource pool, or datastore. You read how to update VMware Tools and upgrade the virtual hardware. You also learned how to use snapshots; run commands in the guest OS, configure Fault Tolerance, open the console of virtual machines, and remove virtual machines.

Finally, we discussed the use of tag categories, tags, and tag assignments. We also discussed the conversion from custom attributes to tag categories, and from annotations to tags and tag assignments.

In the following chapter, we will look at managing virtual networks with PowerCLI.

lock icon
The rest of the chapter is locked

Unlock this book and the full library FREE for 7 days

Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
You have been reading a chapter from
Learning PowerCLI - Second Edition
Published in: Feb 2017Publisher: ISBN-13: 9781786468017
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Robert van den Nieuwendijk

Robert van den Nieuwendijk is an IT veteran from the Netherlands with over thirty years of experience in Information Technology. He holds a bachelor degree in software engineering. After working a few years as a programmer of air traffic control and vessel traffic management systems, he started his own company Van den Nieuwendijk Informatica in 1988. Since then he has worked as a freelance systems administrator of OpenVMS, Windows Server, Linux, and VMware vSphere systems, for Dutch governmental organizations and cloud providers. During winter he is also a ski and snowboard instructor at an indoor ski school. With his background as a programmer, he always tries to make his job easier by writing programs or scripts to perform repeating tasks. In the past, he used the C programming language, OpenVMS DCL, Visual Basic Script and KiXtart to do this. Now, he uses Microsoft PowerShell and VMware PowerCLI for all of his scripting work. Robert is a frequent contributor and moderator at the VMware VMTN Communities. Since 2012 VMware awarded him the vExpert title for his significant contributions to the community and a willingness to share his expertise with others. He has a blog at&nbsp;http://rvdnieuwendijk.com where he writes mainly about VMware PowerCLI, Microsoft PowerShell, and VMware vSphere. If you want to get in touch with Robert, then you can find him on Twitter. His username is @rvdnieuwendijk. Robert is also the author of Learning PowerCLI, Packt Publishing.
Read more about Robert van den Nieuwendijk