Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning PowerCLI

You're reading from   Learning PowerCLI A comprehensive guide on PowerCLI

Arrow left icon
Product type Paperback
Published in Feb 2017
Publisher
ISBN-13 9781786468017
Length 562 pages
Edition 2nd Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Robert van den Nieuwendijk Robert van den Nieuwendijk
Author Profile Icon Robert van den Nieuwendijk
Robert van den Nieuwendijk
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface 1. Introduction to PowerCLI FREE CHAPTER 2. Learning Basic PowerCLI Concepts 3. Working with Objects in PowerShell 4. Managing vSphere Hosts with PowerCLI 5. Managing Virtual Machines with PowerCLI 6. Managing Virtual Networks with PowerCLI 7. Managing Storage 8. Managing High Availability and Clustering 9. Managing vCenter Server 10. Patching ESXi Hosts and Upgrading Virtual Machines 11. Managing VMware vCloud Director and vCloud Air 12. Using Site Recovery Manager 13. Using vRealize Operations Manager 14. Using REST API to manage NSX and vRealize Automation 15. Reporting with PowerCLI

Retrieving a list of all of your virtual machines

Now that we know how to connect to a server, let's do something useful with PowerCLI. Most of the people who begin using PowerCLI create reports, so create a list of all of your virtual machines as your first report. You have to use the Get-VM cmdlet to retrieve a list of your virtual machines. The syntax of the Get-VM cmdlet is as follows. The first parameter set is the default:

Get-VM [[-Name] <String[]>] [-Server <VIServer[]>] 
    [-Datastore <StorageResource[]>] [-Location <VIContainer[]>]
    [-Tag <Tag[]>] [-NoRecursion] [<CommonParameters>]

The second parameter set is for retrieving virtual machines connected to specific virtual switches:

Get-VM [[-Name] <String[]>] [-Server <VIServer[]>] [-VirtualSwitch 
    <VirtualSwitchBase[]>] [-Tag <Tag[]>] [<CommonParameters>]

The third parameter set is for retrieving virtual machines by ID:

Get-VM [-Server <VIServer[]>] -Id <String[]> [<CommonParameters>]

The -Id parameter is required. The fourth parameter set is for retrieving virtual machines by related object:

Get-VM -RelatedObject <VmRelatedObjectBase[]> [<CommonParameters>]

The -RelatedObject parameter is required. You can use these four parameter sets to filter the virtual machines based on name, server, datastore, location, distributed switch, ID, or related object.

Create your first report with the following command:

PowerCLI C:\> Get-VM

This will create a list of all of your virtual machines. You will see the name, power state, the number of CPU's, and the amount of memory in GB for each virtual machine, as shown in the following command-line output:

Name                 PowerState NumCPUs MemoryGB
----                 ---------- -------- --------
Dc1                  PoweredOn  2        4.000
VM1                  PoweredOn  1        0.250
DNS1                 PoweredOn  2        8.000

The Name, PowerState, NumCPU, and MemoryGB properties are the properties that you will see by default if you use the Get-VM cmdlet. However, the virtual machine object in PowerCLI has a lot of other properties that are not shown by default. You can see them all by piping the output of the Get-VM cmdlet to the Format-List cmdlet using the pipe character |. The Format-List cmdlet displays object properties and their values in a list format, as shown in the following command-line output:

PowerCLI C:\> Get-VM -Name DC1 | Format-List -Property *


    Name                    : DC1
PowerState              : PoweredOff
Notes                   :
Guest                   : DC1:
NumCPU                  : 1
CoresPerSocket          : 1
MemoryMB                : 4096
MemoryGB                : 4
VMHostId                : HostSystem-host-10
VMHost                  : 192.168.0.133
VApp                    :
FolderId                : Folder-group-v9
Folder                  : Discovered virtual machine
ResourcePoolId          : ResourcePool-resgroup-8
ResourcePool            : Resources
HARestartPriority       : ClusterRestartPriority
HAIsolationResponse     : AsSpecifiedByCluster
DrsAutomationLevel      : AsSpecifiedByCluster
VMSwapfilePolicy        : Inherit
VMResourceConfiguration : CpuShares:Normal/1000
                          MemShares:Normal/40960
Version                 : v13
PersistentId            : 50399fa1-6d65-a26f-1fd2-b635d0e8610f
GuestId                 : windows9Server64Guest
UsedSpaceGB             : 30.000001807697117328643798828
ProvisionedSpaceGB      : 34.175447797402739524841308594
DatastoreIdList         : {Datastore-datastore-11}
ExtensionData           : VMware.Vim.VirtualMachine
CustomFields            : {}
Id                      : VirtualMachine-vm-46
Uid                     : /VIServer=vsphere.local\administrator@192.
                          168.0.132:443/VirtualMachine=VirtualMachin
                          e-vm-46/
Client                  : VMware.VimAutomation.ViCore.Impl.V1.VimCli
                          Ent

You can select specific properties with the Select-Object cmdlet. Say you want to make a report that shows the Name, Notes, VMHost, and Guest properties for all your virtual machines. You can do that with the following command:

PowerCLI C:\> Get-VM | Select-Object -Property Name,Notes,VMHost,Guest

The output of the preceding command is as follows:

Name              Notes      VMHost        Guest
----              -----      ------        -----
DC1                          192.168.0.133 DC1:
VM1                          192.168.0.134 VM1:
DNS1              DNS Server 192.168.0.134 DNS1:

In PowerShell, parameters can be positional. This means that you can omit the parameter name if you put the parameter values in the right order. In the preceding example, the -Property parameter of the Select-Object cmdlet can be omitted. So the preceding command can also be written as:

PowerCLI C:\> Get-VM | Select-Object Name,Notes,VMHost,Guest

In the examples in this book, I will always use the parameter names.

Suppressing deprecated warnings

You will probably have also seen the following warning messages:

WARNING: The 'Description' property of VirtualMachine type is
    deprecated. Use the 'Notes' property instead.
WARNING: The 'HardDisks' property of VirtualMachine type is
    deprecated. Use 'Get-HardDisk' cmdlet instead.
WARNING: The 'NetworkAdapters' property of VirtualMachine type is
    deprecated. Use 'Get-NetworkAdapter' cmdlet instead.
WARNING: The 'UsbDevices' property of VirtualMachine type is
    deprecated. Use 'Get-UsbDevice' cmdlet instead.
WARNING: The 'CDDrives' property of VirtualMachine type is
    deprecated. Use 'Get-CDDrive' cmdlet instead.
WARNING: The 'FloppyDrives' property of VirtualMachine type is
    deprecated. Use 'Get-FloppyDrive' cmdlet instead.
WARNING: The 'Host' property of VirtualMachine type is deprecated.
    Use the 'VMHost' property instead.
WARNING: The 'HostId' property of VirtualMachine type is deprecated.
    Use the 'VMHostId' property instead.
WARNING: PowerCLI scripts should not use the 'Client' property. The
    property will be removed in a future release.

These warning messages show the properties that should not be used in your scripts because they are deprecated and might be removed in a future PowerCLI release. Personally, I like these warnings because they remind me of the properties that I should not use anymore. But if you don't like these warnings, you can stop them from appearing with the following command:

PowerCLI C:\> Set-PowerCLIConfiguration -DisplayDeprecationWarnings
    $false -Scope User

Using wildcard characters

You can also use wildcard characters to select specific virtual machines. To display only the virtual machines that have names that start with an A or a, type the following command:

PowerCLI C:\> Get-VM -Name A*

Parameter values are not case sensitive. The asterisk (*) is a wildcard character that matches zero or more characters, starting at the specified position. Another wildcard character is the question mark (?), which matches any character at the specified position. To get all virtual machines with a three-letter name that ends with e, use the following command:

PowerCLI C:\> Get-VM -Name ??e

You can also specify some specific characters, as shown in the following command:

PowerCLI C:\> Get-VM -Name [bc]*

The preceding command displays all of the virtual machines that have names starting with b or c. You can also specify a range of characters, as shown in the following command:

PowerCLI C:\> Get-VM -Name *[0-4]

The preceding command lists all of the virtual machines that have names ending with 0, 1, 2, 3, or 4.

Filtering objects

If you want to filter properties that don't have their own Get-VM parameter, you can pipe the output of the Get-VM cmdlet to the Where-Object cmdlet. Using the Where-Object cmdlet, you can set the filter on any property. Let's display a list of all of your virtual machines that have more than one virtual CPU using the following command:

PowerCLI C:\> Get-VM | Where-Object {$_.NumCPU -gt 1}

In this example, the Where-Object cmdlet has a PowerShell scriptblock as a parameter. A scriptblock is a PowerShell script surrounded by braces. In this scriptblock, you see $_. When using commands in the pipeline, $_ represents the current object. In the preceding example, $_ represents the virtual machine object that is passed through the pipeline. $_.NumCPU is the NumCPU property of the current virtual machine in the pipeline. -gt means greater than, so the preceding command shows all virtual machines' objects where the NumCPU property has a value greater than 1.

PowerShell V3 introduced a new, easier syntax for the Where-Object cmdlet. You don't have to use a scriptblock anymore. You can now use the following command:

PowerCLI C:\> Get-VM | Where-Object NumCPU -gt 1

Isn't the preceding command much more like simple English?

Note

In the rest of this book, the PowerShell V2 syntax will be used by default because the V2 syntax will also work in PowerShell V3 and higher versions of PowerShell. If PowerShell V3 syntax is used anywhere, it will be specifically mentioned.

Using comparison operators

In the preceding section, Filtering objects, you saw an example of the -gt comparison operator. In the following table, we will show you all of the PowerShell comparison operators:

Operator

Description

-eq, -ceq, and -ieq

Equal to.

-ne, -cne, and -ine

Not equal to.

-gt, -cgt, and -igt

Greater than.

-ge, -cge, and -ige

Greater than or equal to.

-lt, -clt, and -ilt

Less than.

-le, -cle, and -ile

Less than or equal to.

-Like

Match using the wildcard character (*).

-NotLike

Does not match using the wildcard character (*).

-Match

Matches a string using regular expressions.

-NotMatch

Does not match a string. Uses regular expressions.

-Contains

Tells whether a collection of reference values includes a single test value.

-NotContains

Tells whether a collection of reference values does not include a single test value.

-In

Tells whether a test value appears in a collection of reference values.

-NotIn

Tells whether a test value does not appear in a collection of reference values.

In the preceding table, you see three different operators for some functions. So what is the difference? The c variant is case sensitive. The two-letter variant and the i variant are case-insensitive. The i variant is made to make it clear that you want to use the case insensitive operator.

Using aliases

The Where-Object cmdlet has two aliases: ? and where. Therefore, both the following commands will display a list of all your virtual machines that have more than one virtual CPU:

PowerCLI C:\> Get-VM | ? {$_.NumCPU -gt 1}


PowerCLI C:\> Get-VM | Where NumCPU -gt 1

Note

Using aliases will save you from the trouble of typing in the PowerCLI console. However, it is good practice to use the full cmdlet names when you write a script. This will make the script much more readable and easier to understand.

To see a list of all of the aliases that are defined for cmdlets, type the following command:

PowerCLI C:\> Get-Alias

You can create aliases using the New-Alias cmdlet. For example, to create an alias childs for the Get-ChildItem cmdlet, you can use the following command:

PowerCLI C:\> New-Alias -Name childs -Value Get-ChildItem
You have been reading a chapter from
Learning PowerCLI - Second Edition
Published in: Feb 2017
Publisher:
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 €18.99/month. Cancel anytime