Have you ever had to create 100 virtual machines in a really short period of time, change a setting on all of your hosts, or make an advanced report for your boss to show how full the hard disks of your virtual machines are? If you have, you know that performing these tasks using the vSphere client will take a lot of time. This is where automation can make your job easier. VMware vSphere PowerCLI is a powerful tool that can perform these tasks and much more. And the best thing is that it is free!
VMware vSphere PowerCLI is a command-line interface distributed as a Microsoft Windows PowerShell snap-in. You can use PowerCLI to automate your vSphere hosts, virtual machines, virtual networks, storage, clusters, vCenter Servers, and more.
In this chapter, you will learn:
Downloading and installing PowerCLI
Modifying the PowerShell execution policy
Connecting and disconnecting servers
Using the credential store
Retrieving a list of all of your virtual machines
Retrieving a list of all of your hosts
Before you can install PowerCLI, you have to download the PowerCLI installer from the VMware website. You will need a My VMware account to do this.
Perform the following steps to download PowerCLI:
Visit http://www.vmware.com/go/powercli. On this page, you will find a Resources section.
Click on the vSphere PowerCLI 5.5 link in the Resources section to go to the download page.
Click on the Download button to download PowerCLI.
You have to log in with a My VMware account. If you don't have a My VMware account, you can register for free.
After you log in, you will be taken to the vSphere PowerCLI 5.5 download page. Click on the Download Now button to start downloading PowerCLI.
You have to agree to and accept the terms and conditions outlined in the VMware End User License Agreement. Check the tick box in front of I agree to the terms and conditions outlined in the End User License Agreement and click on Accept to download the PowerCLI installer.
Save the PowerCLI installation file on your local hard disk.
Perform the following steps to install PowerCLI:
Run the PowerCLI installer that you just downloaded.
Click on Yes in the User Account Control window to accept the Do you want to allow the following program to make changes to this computer? option.
PowerCLI requires VMware Remote Console Plug-In and VMware VIX to be installed on your computer. Click on Install to install these products.
Click on Next on the Welcome to the InstallShield Wizard for VMware vSphere PowerCLI window.
Select I accept the terms in the license agreement and click on Next.
If you are using VMware vCloud Director, you can select This feature will be installed on local hard drive for vCloud Director PowerCLI. (If you want, you can change the installation directory by clicking on Change....) Click on Next.
Click on Install to begin the installation.
Click on Finish to exit the installation wizard.
After installing PowerCLI, you will have a VMware vSphere PowerCLI icon on your desktop. If you installed PowerCLI on a 64-bit computer, you will also have a VMware vSphere PowerCLI (32-Bit) icon. Some PowerCLI commands only work in the 32-bit version of PowerCLI. So install both versions.
Besides starting PowerCLI from the icon on your desktop, you can also start PowerCLI from the Start menu. Go to All Programs | VMware | VMware vSphere PowerCLI to launch VMware vSphere PowerCLI or VMware vSphere PowerCLI (32-Bit).
When you start PowerCLI, you will get the following screen:

If you didn't get the text from the screenshot but got some red error messages saying that files cannot be loaded because running scripts is disabled on this system , read the following section to solve this problem. The following screenshot shows the error message that will be displayed:

If this is the first time that you are using Windows PowerShell on the computer on which you installed PowerCLI, you have to change the execution policy to be able to start PowerCLI.
The Windows PowerShell execution policies define when you can run scripts or load configuration files. The possible values for the execution policy are: Restricted
, AllSigned
, RemoteSigned
, Unrestricted
, Bypass
, and Undefined
.
You can check the current execution policy setting with the following command:
PowerCLI C:\> Get-ExecutionPolicy
Get-ExecutionPolicy
is a Windows PowerShell commandlet (cmdlet). Cmdlets are commands built into PowerShell or PowerCLI. They follow a verb-noun naming convention. The get cmdlets receives information about the item that is specified as the noun part of the cmdlet.
Set the execution policy to RemoteSigned
to be able to start PowerCLI and run scripts written on the local computer with the Set-ExecutionPolicy –ExecutionPolicy RemoteSigned
command, as shown in the next screenshot.
Note
You have to run the Set-ExecutionPolicy –ExecutionPolicy RemoteSigned
command from a PowerShell or PowerCLI session that you started using the Run as Administrator option, or you will get the following error message:
Set-ExecutionPolicy : Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied.
If you are using both the 32-bit and the 64-bit versions of PowerCLI, you have to run this command in both versions.
In the next screenshot of the PowerCLI console, you will see the output of the Set-ExecutionPolicy –ExecutionPolicy RemoteSigned
command if you run this command in a PowerCLI session started with "Run as Administrator".

You can get more information about execution policies by typing the following command:
PowerCLI C:\> Get-Help about_Execution_Policies
To get more information about signing your scripts, type the following command:
PowerCLI C:\> Get-Help about_signing
Before you can do useful things with PowerCLI, you have to connect to a vCenter Server or an ESXi server. And if you are finished, it is a good practice to disconnect your session. We will discuss how to do this in the following sections.
If you are not connected to a vCenter or an ESXi server, you will get an error message if you try to run a PowerCLI cmdlet. Let's try to retrieve a list of all of your datacenters using the following command:
PowerCLI C:\> Get-Datacenter
The output of the preceding command is as follows:
Get-Datacenter : 12/19/2013 7:29:36 PM Get-Datacenter Youare not currently connected to any servers. Please connect firstusing a Connect cmdlet. At line:1 char:1 + Get-Datacenter + ~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (:) [Get-Datacenter], ViServerConnectionException + FullyQualifiedErrorId :Core_BaseCmdlet_NotConnectedError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetDatacenter
You see that this gives an error message. You first have to connect to a vCenter Server or an ESXi server using the Connect-VIServer
cmdlet. If you have a vCenter Server, you only need to connect to the vCenter Server and not to the individual ESXi servers. It is possible to connect to multiple vCenter Servers or ESXi servers at once. The Connect-VIServer
cmdlet has the following syntax:
Connect-VIServer [-Server] <String[]> [-Port <Int32>] [-Protocol <String>] [-Credential <PSCredential>] [-User <String>] [-Password <String>] [-Session <String>] [-NotDefault] [-SaveCredentials] [-AllLinked] [-Force] [<CommonParameters>] Connect-VIServer -Menu [<CommonParameters>]
As you can see, the Connect-VIserver
cmdlet has two parameter sets: Default
and Menu
. In the Default
parameter set, the –Server
parameter is required. In the Menu
parameter set, the –Menu
parameter is required. You cannot combine parameters from the Default
parameter set with the Menu
parameter set.
Let's first try to connect to a vCenter Server with the following cmdlet:
PowerCLI C:\> Connect-VIServer –Server 192.168.0.132
192.168.0.132
is the IP address of the vCenter Server in my home lab. Replace this IP address with the IP address or DNS name of your vCenter or ESXi server.
The preceding command will pop up a window in which you have to specify server credentials to connect to your server if your Windows session credentials don't have rights on your server. Enter values for User name and Password and click on OK.
If you specified valid credentials, you will get output similar to the following:
Name Port User ---- ---- ---- 192.168.0.132 443 root
You can also specify a username and password on the command line as follows:
PowerCLI C:\> Connect-VIServer –Server 192.168.0.132 -User admin -Password pass
You can also save the credentials in a variable with the following command:
PowerCLI C:\> $Credential = Get-Credential
The preceding command will pop up a window in which you can type the username and password.

You can now use the $Credential
variable to connect to a server using the –Credential
parameter, as follows:
PowerCLI C:\> Connect-VIServer –Server 192.168.0.132 –Credential$Credential
You can also use the PowerCLI credential store. This will be discussed in a later section in this chapter.
The default protocol that the Connect-VIServer
cmdlet uses is HTTPS. If you want to make a connection with the HTTP protocol, you can do that with the following command:
PowerCLI C:\> Connect-VIServer –Server 192.168.0.132 –Protocol http
If you have multiple vCenter Servers in Linked Mode, you can use the Connect-VIServer –AllLinked
parameter to connect all of these vCenter Servers at once, as follows:
PowerCLI C:\> Connect-VIserver -Server 192.168.0.132 -Credential$Credential -AllLinked
The Connect-VIServer –Menu
command gives you a list of previously connected servers from which you can pick one, as shown in the following command line:
PowerCLI C:\> Connect-VIServer -Menu Select a server from the list (by typing its number and pressing Enter): [1] 192.168.0.132 [2] 192.168.0.133
It is possible in PowerCLI to connect to multiple servers at once. You can do this by specifying more than one server, as follows:
PowerCLI C:\> Connect-VIServer –Server vCenter1,vCenter2
The first time you try to do this, you will get the following message:
Working with multiple default servers? Select [Y] if you want to work with more than one default servers. In this case, every time when you connect to a different server using Connect-VIServer, the new server connection is stored in an array variable together with the previously connected servers.When you run a cmdlet and the target servers cannot be determined from the specified parameters, the cmdlet runs against all servers stored in the array variable. Select [N] if you want to work with a single default server. In this case, when you run a cmdlet and the target servers cannot be determined from the specified parameters, the cmdlet runs against the last connected server. WARNING: WORKING WITH MULTIPLE DEFAULT SERVERS WILL BE ENABLED BYDEFAULT IN A FUTURE RELEASE. You can explicitly set your own preference at any time by using the DefaultServerMode parameter of Set-PowerCLIConfiguration. [Y] Yes [N] No [S] Suspend [?] Help (default is "Y"):
Press Enter or type Y to work with multiple default servers.
As the message says, you can always connect to multiple servers but your commands will only work against the last server you connected to unless you have enabled working with multiple servers.
You can see the current value of DefaultServerMode
with the Get-PowerCLIConfiguration
cmdlet:
PowerCLI C:\> Get-PowerCLIConfiguration
If you want to change the DefaultServerMode from single to multiple, you can do that with the Set-PowerCLIConfiguration
cmdlet. The cmdlet has the following syntax:
Set-PowerCLIConfiguration [-ProxyPolicy <ProxyPolicy>][-DefaultVIServerMode <DefaultVIServerMode>][-InvalidCertificateAction <BadCertificateAction>] [-DisplayDeprecationWarnings [<Boolean>]] [-WebOperationTimeoutSeconds <Int32>] [-VMConsoleWindowBrowser <String>] [-Scope <ConfigurationScope>] [-WhatIf] [-Confirm] [<CommonParameters>]
Change the DefaultServerMode from single to multiple with the following command:
PowerCLI C:\> Set-PowerCLIConfiguration -DefaultVIServerMode Multiple-Scope User
All of the servers that you are currently connected to are stored in the variable $global:DefaultVIServers
. If DefaultVIServerMode
is set to multiple, your PowerCLI cmdlets will run against all servers stored in the $global:DefaultVIServers
variable.
The last server you are connected to is stored in the variable $global:DefaultVIServer
. If DefaultVIServerMode
is set to single
, your PowerCLI cmdlets will only run against the server stored in the $global:DefaultVIServer
variable.
If your vCenter Server does not have valid server certificates, the Connect-VIserver
cmdlet will display some warning messages, as shown in the following screenshot:

It is a good practice is to supply your vCenter Server and ESXi servers with valid certificates. You can find information on how to do this in the VMware Knowledge Base article, Implementing CA signed SSL certificates with vSphere 5.x (2034833) at http://kb.vmware.com/kb/2034833.
If you don't have valid certificates, you can easily suppress the warning messages using the Set-PowerCLIConfiguration
cmdlet with the following command:
PowerCLI C:\ > Set-PowerCLIConfiguration -InvalidCertificateAction Ignore
This will modify InvalidCertificationAction
in the AllUsers
scope. You have to run this command using the Run as Administrator PowerCLI session. Otherwise, you will get the following error message:
Set-PowerCLIConfiguration : Only administrators can change settings for all users. At line:1 char:1 + Set-PowerCLIConfiguration -InvalidCertificateAction Ignore + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Set-PowerCLIConfiguration], InvalidArgument + FullyQualifiedErrorId : VMware.VimAutomation.ViCore.Types.V1.ErrorHandling.InvalidArgument,VMware.VimAutomation.ViCore.Cmdlets.Commands.SetVIToolkitConfiguration
To disconnect from a vSphere server, you have to use the Disconnect-VIServer
cmdlet. The Disconnect-VIServer
cmdlet has the following syntax:
Disconnect-VIServer [[-Server] <VIServer[]>] [-Force] [-WhatIf][-Confirm] [<CommonParameters>]
To disconnect all of your server connections, type the following command:
PowerCLI C:\> Disconnect-VIServer -Server * -Force
The output of the preceding command is as follows:
Confirm Are you sure you want to perform this action? Performing operation "Disconnect VIServer" on Target "User: root,Server: 192.168.0.132, Port: 443". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?]Help (default is "Y"):
Type Y or Enter to disconnect from the server.
If you don't want to be prompted with Are you sure you want to perform this action?, you can use the –Confirm:$false
option as follows:
PowerCLI C:\> Disconnect-VIServer -Server * -Force –Confirm:$false
It may be that you want to disconnect only one session and not all. In that case, specify the server name or IP address of the server you want to disconnect. The following command only disconnects the latest session from server 192.168.0.132
:
PowerCLI C:\> Disconnect-VIServer –Server 192.168.0.132
Disconnecting one or more sessions will also change the value of the $global:DefaultVIServers
and $global:DefaultVIServer
variables.
To see the current setting of InvalidCertificationAction
, you can use the Get-PowerCLIConfiguration
cmdlet. The syntax of this cmdlet is as follows:
Get-PowerCLIConfiguration [-Scope <ConfigurationScope>] [<CommonParameters>]
The following example will retrieve the PowerCLI configuration and shows the InvalidCertificateAction
value for all scopes:
PowerCLI C:\> Get-PowerCLIConfiguration | >> Select-Object -Property Scope,InvalidCertificateAction,DisplayDeprecationWarnings | >> Format-Table -AutoSize >> Scope InvalidCertificateAction DisplayDeprecationWarnings ----- ------------------------ -------------------------- Session Ignore True User Ignore True AllUsers Unset
As you can see in the output, there are three different scopes for which you can modify the PowerCLI configuration: Session
, User
, and AllUsers
. The Set-PowerCLIConfiguration
cmdlet will modify the AllUser
scope if you don't specify a scope.
The DisplayDeprecationWarnings
property shown in the preceding output will be discussed in a later section in this chapter.
If you are logged in to your computer with a domain account, you can use your Windows session credentials to connect to a vCenter or ESXi server. If you are not logged in to your computer with a domain account or your domain account has no rights in vSphere, you have to supply account information every time you connect to a vCenter or ESXi server.
To prevent you from having to do this, you can store credentials in the credential store. These stored credentials will be used as default if you connect to a server that is stored in the credential store. You can use the –SaveCredentials
parameter of the Connect-VIServer
cmdlet to indicate that you want to save the specified credentials in the local credential store, as follows:
PowerCLI C:\> Connect-VIServer –Server 192.168.0.132 -User admin-Password pass -SaveCredentials
You can also create a new entry in the credential store with the New-VICredentialStoreItem
cmdlet:
PowerCLI C:\> New-VICredentialStoreItem -Host 192.168.0.132-User Admin -Password pass
You can not only store credentials for vCenter Servers but also for ESXi servers, using the following command:
PowerCLI C:\> New-VICredentialStoreItem -Host ESX1–User root –Password vmware
To get a listing of all of your stored credentials, type the following command:
PowerCLI C:\> Get-VICredentialStoreItem
And to remove a stored credential you can use the following command:
PowerCLI C:\> Remove-VICredentialStoreItem –Host ESX1 –User root
The stored credentials are stored in a file on your computer. The default credential store file location is: %APPDATA%\VMware\credstore\vicredentials.xml
. But it is also possible to create other credential store files. You can see the contents of the default credential store file with the following command:
PowerCLI C:\> Get-Content -Path $env:APPDATA\VMware\credstore\vicredentials.xml
The passwords stored in a credential store file are encrypted. But you can easily retrieve the stored passwords with the following command:
PowerCLI C:\> Get-VICredentialStoreItem | >> Select-Object -Property Host,User,Password
So, if your computer is also used by other users and you are not sure that the information in the credential store file cannot be read by other people, it might be better not to use this feature.
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:
Get-VM [[-Name] <String[]>] [-Server <VIServer[]>] [-Datastore <StorageResource[]>] [-Location <VIContainer[]>][-Tag <Tag[]>] [-NoRecursion] [<CommonParameters>] Get-VM [[-Name] <String[]>] [-Server <VIServer[]>] [-DistributedSwitch <DistributedSwitch[]>] [-Tag <Tag[]>][<CommonParameters>] Get-VM [-Server <VIServer[]>] -Id <String[]> [<CommonParameters>] Get-VM -RelatedObject <VmRelatedObjectBase[]> [<CommonParameters>]
As you can see, the Get-VM
cmdlet has four different parameter sets. The names of these parameter sets are: Default
, DistributedSwitch
, ById
, and RelatedObject
. You can use these parameter sets to filter the virtual machines based on name, server, data store, 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, 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 Num CPUs MemoryGB ---- ---------- -------- -------- Dc1 PoweredOn 2 8.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 * PowerState : PoweredOn Version : v10 Description : Domain controller Notes : Domain controller Guest : DC1: Microsoft Windows Server 2012 (64-bit) NumCpu : 2 MemoryMB : 8192 MemoryGB : 8 HardDisks : {Hard disk 1, Hard disk 2} NetworkAdapters : {Network adapter 1} UsbDevices : {} CDDrives : {CD/DVD drive 1} FloppyDrives : {} Host : ESX1.blackmilktea.com HostId : HostSystem-host-10 VMHostId : HostSystem-host-10 VMHost : ESX1.blackmilktea.com VApp : FolderId : Folder-group-v9 Folder : Discovered virtual machine ResourcePoolId : ResourcePool-resgroup-8 ResourcePool : Resources PersistentId : 50289ad0-a545-1299-5a75-811049f98276 UsedSpaceGB : 71.268582795746624469757080078 ProvisionedSpaceGB : 78.204129670746624469757080078 DatastoreIdList : {Datastore-datastore-14} HARestartPriority : ClusterRestartPriority HAIsolationResponse : AsSpecifiedByCluster DrsAutomationLevel : AsSpecifiedByCluster VMSwapfilePolicy : Inherit VMResourceConfiguration : CpuShares:Normal/2000 MemShares:Normal/81920 Name : DC1 CustomFields : {[Application code, ], [CreatedBy, Unknown], [CreatedOn, Unknown], [Function, ]...} ExtensionData : VMware.Vim.VirtualMachine Id : VirtualMachine-vm-16 Uid : /VIServer=blackteamilk\admin@192.168.0.132:443/VirtualMachine=VirtualMachine-vm-16/ Client : VMware.VimAutomation.ViCore.Impl.V1.VimClient
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:
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
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 an "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 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 the virtual machines that have names ending with 0, 1, 2, 3, or 4.
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?
In the previous section, 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 |
---|---|
|
Equals |
|
Not equals |
|
Greater than |
|
Greater than or equal to |
|
Less than |
|
Less than or equal to |
In the preceding table, you see three different operators for all 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.
The Where-Object
cmdlet has an alias, ?
. 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-Object NumCPU -gt 1
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 your own 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
Similar to the Get-VM
cmdlet, which retrieves your virtual machines, is the Get-VMHost
cmdlet, which displays your hosts. The Get-VMHost
cmdlet has the following syntax:
Get-VMHost [[-Name] <String[]>] [-NoRecursion] [-Datastore <StorageResource[]>] [-State <VMHostState[]>] [-Location <VIContainer[]>] [-Tag <Tag[]>] [-Server <VIServer[]>] [<CommonParameters>] Get-VMHost [[-Name] <String[]>] [-DistributedSwitch <DistributedSwitch[]>] [-Tag <Tag[]>] [-Server <VIServer[]>] [<CommonParameters>] Get-VMHost [[-Name] <String[]>] [-NoRecursion] [-VM <VirtualMachine[]>] [-ResourcePool <ResourcePool[]>] [-Datastore <StorageResource[]>] [-Location <VIContainer[]>] [-Tag <Tag[]>] [-Server <VIServer[]>] [<CommonParameters>] Get-VMHost -Id <String[]> [-Server <VIServer[]>] [<CommonParameters>]
You see that there are four different parameter sets. They are named: Default
, DistributedSwitch
, SecondaryParameterSet
, and ById
. Don't mix parameters from different sets or you will get an error as follows:
PowerCLI C:\> Get-VMHost -Id HostSystem-host-22 -Name 192.168.0.133 Get-VMHost : Parameter set cannot be resolved using the specifiednamed parameters. At line:1 char:1 + Get-VMHost -Id HostSystem-host-22 -Name 192.168.0.133 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Get-VMHost], ParameterBindingException + FullyQualifiedErrorId :AmbiguousParameterSet,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetVMHost
To get a list of all of your hosts, type the following command:
PowerCLI C:\> Get-VMHost
By default, only the Name
, ConnectionState
, PowerState
, NumCPU
, CpuUsageMhz
, CpuTotalMhz
, MemoryUsageGB
, MemoryTotalGB
, and Version
properties are shown. To get a list of all of the properties, type the following command:
PowerCLI C:\> Get-VMHost | Format-List –Property * State : Connected ConnectionState : Connected PowerState : PoweredOn VMSwapfileDatastoreId : VMSwapfilePolicy : Inherit ParentId : ClusterComputeResource-domain-c7 IsStandalone : False Manufacturer : VMware, Inc. Model : VMware Virtual Platform NumCpu : 2 CpuTotalMhz : 4588 CpuUsageMhz : 54 LicenseKey : 00000-00000-00000-00000-00000 MemoryTotalMB : 2047.48828125 MemoryTotalGB : 1.999500274658203125 MemoryUsageMB : 965 MemoryUsageGB : 0.9423828125 ProcessorType : Intel(R) Core(TM) i5-2415M CPU @ 2.30GHz HyperthreadingActive : False TimeZone : UTC Version : 5.5.0 Build : 1331820 Parent : Cluster01 VMSwapfileDatastore : StorageInfo : HostStorageSystem-storageSystem-22 NetworkInfo : localhost:sitecomwl306 DiagnosticPartition : mpx.vmhba1:C0:T0:L0 FirewallDefaultPolicy : VMHostFirewallDefaultPolicy:HostSystem-host-22 ApiVersion : 5.5 Name : 192.168.0.133 CustomFields : {[AutoDeploy.MachineIdentity, ]} ExtensionData : VMware.Vim.HostSystem Id : HostSystem-host-22 Uid : /VIServer=root@192.168.0.132:443/VMHost=HostSystem-host-22/ Client : VMware.VimAutomation.ViCore.Impl.V1.VimClient DatastoreIdList : {Datastore-datastore-23}
You can use the Get-VMHost
parameters or the Where-Object
cmdlet to filter the hosts you want to display, as we did with the Get-VM
cmdlet.
Instead of displaying the output of your PowerCLI commands in the PowerCLI console, you can also display the output in a grid view. A grid view is a pop up that looks like a spreadsheet with rows and columns. To display the output of the Get-VMHost
cmdlet in a grid view, type the following command:
PowerCLI C:\> Get-VMHost | Out-GridView
The preceding command opens the window of the following screenshot:

You can create filters to display only certain rows, and you can sort columns by clicking on the column header. You can also reorder columns by dragging and dropping them. In the next screenshot, we created a filter to show only the hosts with a CpuUsageMhz
value greater than or equal to 70. We also changed the order of the ConnectionState and PowerState columns.

Isn't that cool?
In this chapter, we looked at downloading and installing PowerCLI and modified the PowerShell execution policy to be able to start PowerCLI. Then we covered how to connect to and disconnect from a server and introduced the credential store to save you from having to specify credentials when you connect to a server. You also learned how to get a list of your virtual machines or hosts and how to stop deprecated warnings. You learned all of the PowerShell comparison operators and found out about aliases for cmdlets. Finally, we concluded the chapter with grid views.
In the next chapter, we will introduce some basic PowerCLI concepts.