VCAP study notes – section 8.1, PowerCLI

Print Friendly

PowerCLI has been increasingly popular due to the need to automate larger vSphere environments. This section, more than most on the VCAP-DCA blueprint is one where you have to know what you’re doing – writing code can’t be done in theory, you have to get stuck in and play with it.

The main references for this section are the VMware PowerCLI homepage and the VMware PowerCLI Administration guide. PowerCLI has received extensive blog coverage from numerous people far more experienced than me – check out Virtu-Al, Luc Dekkens, Hal Rottenberg or Jonathan Medd’s blogs for more info than you can handle….

Installing PowerCLI

PowerCLI is simply an extension to Microsoft’s Powershell environment so installation consists of installing Powershell (it’s built into Windows 2008 onwards) and then adding PowerCLI;

Client requirements:

  • WinXP SP2, Win2k3 or greater
  • 32 or 64 bit
  • .NET framework v2.0 SP1 (or greater)
  • Powershell v1 or v2

Server requirements:

  • ESX or ESXi v3.0, vCentre 2.01 (or greater)

By default Powershell restricts script execution. Use this command to allow local scripts but require signing for remote scripts;

Set-ExecutionPolicy RemoteSigned

PowerCLI is a command line environment, but you can also install PowerGUI for a graphical shell, or Visioncore’s Virtualisation EcoShell (VESI). Both come with script editors offering syntax highlighting and debugging facilities. Powershell v2 comes with the Powershell integrated Scripting Environment (ISE) which offers similar functionality. All three are free. The VESI can import pre-supplied powerpacks such as Al Renouf’s Community Powerpack.

PowerCLI runs as a webservice so needs access from the management workstation on ports 80 and 443 to the ESX hosts or vCentre. Scripts can be run against either hosts or the vCentre server.

As mentioned above PowerCLI is simply a group of .NET classes bundled as a snapin to Powershell.  Use the following command to add the snapin to a running Powershell session;

Add-PSSnapIn vmware.vimautomation.core (or Add-PSSnapin vmware*)

To confirm if the snapin is available use the following command;

Get-PSSnapIn –registered

Use at the Powershell prompt to check the installed PS version;


Note: if you’re using the free edition of ESXi then PowerCLI can only read information (ie you can’t make any configuration changes)

Installing Update Manager Powershell library

Installing the Update Manager cmdlets is a separate installation (download here). It adds a second snapin (VMware.VUMautomation) and has the same requirements for installation as PowerCLI.

Update Manager cmdlets are only supported on vSphere 4.0u1 or newer.

Cmdlet concepts

cmdlets are the commands available in PowerCLI. They give full access to the VI SDK – almost anything you can do in the VI client can be done with PowerCLI. You can also do some things you can’t do in the VI client – for instance you can move a template without converting through to VM.

Cmdlets can be used both interactively at the command line and via scripts. As of vSphere 4.0 Update1 there are over 200 cmdlets. A cmdlet provides a simplified interface into the full, underlying .NET objects.  Cmdlets are referred to as Automation Objects as opposed to the more comprehensive objects in the SDK (known as Managed or View objects).

The vSphere SDK has two main types of objects;

  • Managed objects provide both methods and properties
  • Data objects provide only properties

Variables in Powershell are not case sensitive, and start with a ‘$’ symbol. There are four main types;

  • Automatic variables. These hold state information about PowerCLI and are set automatically (hence the name!). Includes variables such as $home (current users home directory), $profile (config file locations for Powershell), and $pwd (the working directory)
    D:\> $profile | Get-Member -MemberType NoteProperty | ft Name
    D:\> $DefaultVIServer | ft -AutoSize
    Name          Port User
    ----          ---- ----
    virtualcentre 443  THEFUNKYSITE\egrigson
  • Preference variables. Variables that customise the behaviour of PowerCLI. Includes variables such as $WarningPreference and $WhatIfPreference. Example;
    get-item -path variable:* (show all Preference variables) $WhatIfPreference="Continue"
  • Environment variables. These hold information about the environment PowerCLI is running in, ie. the local computer. Includes variables such as $ComputerName, $WinDir, and $Path. Examples;
    get-item -path env:* (show all environment variables)
    $var = $env:path (set $var equal to the $path environment variable)
  • User created variables. These are the ones you’ll use for your own purposes both interactively and via scripts. Example;

    $myHost = Get-VM TestVM

$DefaultVIServer is a particularly useful variable which points to the currently connected ESX host or vCentre server. It can be an array pointing to multiple hosts (vSphere 4.0U1 and newer). A useful property is $DefaultVIServer.IsConnected to check if a connection is active.

Type ‘help about_variables’, ‘help about environment_variables’ or ‘help about_automatic_variables’ in a Powershell window for more information.

Web Service Access cmdlets

Sometimes a cmdlet won’t provide all the functionality you need or there won’t be a cmdlet at all – in these cases you can use the Get-View cmdlet to access the API directly. This grants you access to much greater functionality at the cost of a steeper learning curve. The counterpart to Get-View is Get-VIObjectbyVIView which, given a complex API object returns the ‘simpler’ object typically used with PowerCLI cmdlets. Not only do you get greater functionality but often it’s faster too.

Combined with ‘cmdlet binding’ (a feature of PowerShell v2) this allow you to write your own cmdlets. A collection of advanced functions using cmdlet binding can be saved in a .PSM1 file and imported using the Import-Module cmdlet.

To use Get-View effectively you need to know what API calls are available. You can browse the API using the Managed Object Browser (MOB) – http://vCentre/mob or http://esxhost/mob or you can refer to VMware’s online API guide. For a tutorial see vInternals excellent series of articles.

Typical operations that used to (or still do) require Get-View;

  • converting a VM to a template (rather than cloning to template)
  • powering down an ESX host (as of vSphere 4.0U1 there is now a Stop-VMHost cmdlet)
  • Enabling vMotion on a host (can now be done via Set-VMHostNetworkAdapter)

Datastore and Inventory providers

‘Powershelldrives’ are navigational structures much like a directory tree in a filesystem. Can be written by third parties – common datastore providers are;

  • vmstore: The DatastorePSDrive. Lets you navigate the VI Datastores.
  • vi: The Inventory PSDrive. Lets you navigate the VI folder structure.
  • env: Environment variables
  • variable: Powershell variables
  • HKCU: The current user’s Windows registry key
  • AD: Active Directory (W2k8 R2 onwards)

cmdlets: Get-PSDrive, New-PSDrive, Remove-PSDrive

The PowerCLI Admin Guide states that operations in Datastore provider are case sensitive but in my tests case was irrelevant.

When using the PSDrives, the objects can be treated just like files;

  • Del <vm> Delete a VM
  • Ren<vm> Rename a VM
  • Dir<vm> | Start-VM Start all the VMs in the current directory

One exception to this is copying files to or from a datastore. To do this use the Copy-DatastoreItemcmdlet;

Copy-DatastoreItem vmstore:\MyDC\NFSMount\VM* c:\VMBackup

Note: The datastore providers have only recently become fully supported and are very slow!

Powershell and PowerCLI cmdlets

The following are general purpose cmdlets in Powershell (rather then PowerCLI specific). It’s worth knowing how these work as you’ll find yourself using them all the time;

  • Get-Task, Wait-Task
  • Get-Content
  • Out-File
  • Format-Table, Format-List, Format-Custom (shows everything, particularly useful with Get-View)
  • Select-Object, Where-Object
  • Help-Object

You should be familiar with using the –whatif and –confirm parameters, along with the $ErrorActionPreference and $WarningPreference variables.

Basic PowerCLI cmdlets

This section lists the ‘basic’ cmdlets covered in the vSphere PowerCLI Administration guide. As it’s explicitly listed on the blueprint assume you’ll need to be familiar with all these cmdlets;

  • Connect-VIServer, Disconnect-VIServer
  • Get-VM, New-VM, Set-VM, Stop-VM, Start-VM, Move-VM (vMotion and svMotion)
  • Get-VMHost, Add-VMHost, Remove-VMHost, Restart-VMHost, Set-VMHost
  • Get-ResourcePool, Set-ResourcePool, Remove-ResourcePool
  • Get-Datastore, Set-Datastore, Remove-Datastore
  • Get-DRSRecommendation, Apply-DRSRecommendation
  • Get-VMGuest, Suspend-VMGuest, Shutdown-VMGuest, Restart-VMGuestNOTE: Set-VMHost is used to put a host in maintenance mode NOTE: Set-VM –Snapshot is used to revert a VM to a previous snapshot. NOTE: no Start-VMGuest, use Start-VM instead
Advanced PowerCLI cmdlets

These cmdlets are covered in the Advanced cmdlets section of the Administration guide, so again are explicitly covered in the blueprint.

  • Get-Folder, New-Folder, Remove-Folder, Move-Folder, Set-Folder
  • Get-Cluster, Set-Cluster (used to enable HA, DRS etc), New-Cluster
  • Get-Template, Set-Template, New-Template.
  • Get-Task, Stop-Task, Wait-Task (VI tasks such as moving a VM, adding a folder etc)
  • New-Harddisk, Remove-Harddisk
  • New-Snapshot, Get-Snapshot, Remove-Snapshot
  • Get-VMHostAdvancedConfiguration, Set-VMHostAdvancedConfiguration
  • New-VMHostProfile, Get-VMHostProfile, Apply-VMHostProfile, Test-VMHostProfileCompliance, Export-VMHostProfile, Import-VMHostProfile, Remove-VMHostProfile
  • Get-VMHostNetwork, Set-VMHostNetwork
  • Get-VirtualSwitch, Set-VirtualSwitch, Remove-VirtualSwitch
  • New-StatsInterval, Get-Stat, Get-StatType
  • Get-NICTeamingPolicy, Set-NICTeamingPolicy – used to set teaming policy, not exposed via other cmdlets

NOTE: Use Set-Template-ToVM to convert a template to a VM rather than clone.To convert a VM to a template rather than clone you have to use ‘Get-VM <VMname> | Get-View | $_.MarkAsTemplate()’ (a method exposed by the full object).

NOTE: When working with folders you’ll see references to ‘blue’ and ‘yellow’ folders which are named due to the colours used in the VI clietn. A blue folder can only contain VMs and templates whereas a yellow folder can contain datacenters, hosts, VMs, and clusters. If you check the folder’s properties you’ll see anIsChildTypeVM property which can be used to distinguish the two types. You can also use the Inventory PSDrive to see the base ‘vm’ or ‘host’ folder which corresponds to the VM and Hosts views respectively.

Update Manager cmdlets
  • Get-Baseline, Attach-Baseline, Detach-Baseline, Remove-Baseline
  • Get-Patch, Download-Patch, Stage-Patch
  • Get-PatchBaseline, New-PatchBaseline, Set-PatchBaseline
  • Remediate-Inventory, Scan-Inventory
  • Get-Compliance
Finding the cmdlet you need

Often you don’t know what cmdlets to choose for a particular task. There are some basic methods for finding the options available;

Show any help entries (or commands) which contain the keyword ‘drs’;

#show any commands containing the word drs
help *drs*	

#only show commands from modules beginning with string 'vm' (ie VMware modules!)
get-command *drs* –module vm*

#show the properties and methods of an object
get-vm MyVM | get-member
Code Examples

Get a list of available commands containing the keyword ‘Guest’ in the VMware snapins

Get-Command –Module vmware* -Name *Guest*

Reverting a VM to a snapshot

Get-VM <myVM> | Set-VM –snapshot <snapshot name> -confirm:$false

Creating a ‘blue’ VM folder

Get-Datacenter<myDC> | Get-Folder vm | New-Folder <myNewFolder>

Converting a VM to a template

Get-VM <myVM> | Get-View | % {$_.MarkAsTemplate()}

Converting a template to a VM

Get-Template <myTemplate> | Set-Template –toVM

Putting a host into maintenance mode

Get-VMHost<myHost> | Set-VMHost –state Maintenance

vMotioning a VM

Get-VM <vm> | Move-VM –Destination <new host>

Storage vMotion

Get-VM <vm> | Move-VM –Datastore<new datastore>

Show the possible migration settings for a host

Get-VMHostAdvancedConfiguration –vmhost<vmhost> -Name Migrate*

Copy the advanced ‘Migration’ settings from one host to another

Set-VMHostAdvancedConfiguration –vmhost<destHost> -Hashtable (Get-VMHostAdvancedConfiguration –vmhost<srcHost> -name Migrate*)

Get the physical adaptors in a given ESX host

Get-VMHost<host> | Get-VMHostNetwork | Select PhysicalNic,Name


Searching a hashtable (key/value pairs, such as those returned by Get-VMHostAdvancedConfiguration) is slightly different from searching scalar values. The code below will only search the keys, not the assigned values. It also doesn’t accept wildcards;

$hashtable = Get-VMHostAdvancedConfiguration –vmhost<vmhost>
$hashtable.containsKey(“Migrate.NetTimeout”) #Returns TRUE if the key exists
$hashtable.GetEnumerator() | Sort Name		#Sorts the hashtable

Hashtables are used with the Filter parameter for Get-View.

Running tasks inside the guest OS

While the VI API (which PowerCLI accesses) is very powerful there are some operations it can’t do, namely interactions with the guest OS running inside a VM (both Windows and Linux). This is where the VIX API comes in, and it’s available via the VMRun.exe command and a couple of associated PowerCLI cmdlets. A couple of useful links;

What is the VIX and why use it? (VMware blog)

VMware VIX APIs – Managing and Automating Guest OS (48 min video)

PowerCLI installs v1.6.2 of the VIX API automatically but you can download alternative versions of the software for Windows or Linux here (PowerCLI only supports v1.6.2 although the latest is 1.10). The latest version supports the following products;

  • vSphere 4.1
  • Fusion 3.1
  • VMServer 2.0
  • VMware Workstation 7.1

The VIX API lets you do a few operations that would be impossible with the VI API;

  • Run a batch file inside Windows (MS-DOS .BAT files) or Linux (Bash scripts)
  • Run a program inside a guest OS
  • Copy files to/from a guest (NOTE: the guest does NOT need network access configured so long as the VMTools are running)
  • List (and optionally kill) processes in the guest OS

The following cmdlets leverage the VIX API and are only available in vSphere 4.0U1 onwards;

  • Invoke-VMScript (-ScriptType can be Powershell (default for Win VMs), Bat or Bash (default for Linux).
  • Copy-VMGuestFile, Get-VMGuestRoute, Set-VMGuestRoute, New-VMGuestRoute, Remove-VMGuestRoute
  • Get-VMGuestNetworkInterface, Set-VMGuestNetworkInterface

NOTE: All the cmdlets which utilise the VIX API require authentication on both the host and the guest.

Requirements on the client;

  • VMware VIXv1.6.2 must be installed (NOTE: PowerCLIshould install this version during install but if you run VMware Workstation or Server they may have installed a newer version. You’ll need to install this older version if you want the PowerCLIcmdlets to work)
  • PowerCLI installed and working
  • Only 32bit version of PowerCLI is supported for Invoke-VMScriptand Copy-VMGuestFile(but x86 version can be run on an x64 client)

Requirements on the guest

  • Must know valid credentials for the ESX server hosting the VM
  • Must know valid credentials for the guest OS (local or domain is OK for Windows VMs)
  • VM must be powered on
  • Help for Invoke-VMScript says that Powershell must be installed, but running against a W2k3 server worked fine without. You may also need to reboot the VM after installing Powershell (according to cmdlet help)
  • VMTools should be up to date and running in the guest OS (NOTE. Running against an old version can cause the console to lockup according to the vSphere 4.0u1 release notes)
  • The underlying ESX host must be v3.5U2 or greater.

Syntax and examples

vmrun –T server –h –u<username> -p <password in plain text!><command>

Some of the more common commands are listed below (see the VMware docs for all options);

start | stop | restart |suspend | register | unregister | runProgramInGuest | runScriptInGuest

Copy a file from a guest OS to a local file (using VMTools rather than VM network)

Copy-VMGuestFile –Source c:\test.txt –Destination c:\ -GuestToLocal -VM (Get-VM <vm>) -HostUser root –HostPassword<password> -GuestUseregrigson -GuestPassword<password>

Run a script inside the guest OS

Invoke-VMScript –vm (Get-VM <vm) –ScriptText “example.bat” –HostUser root –HostPassword<password> -GuestUseregrigson –GuestPassword<password> -ScriptType Bat

Some good examples courtesy of A. Mikkelson


VMware Guest Console (available via VMware Labs) uses VIX API to offer a GUI for the above tasks.

Demo video of using Invoke-VMScript from Carter Shanklin (PowerCLI Product Manager)

You can disable guest operations on a per VM or per host basis but this breaks functionality in VMware Update Manager and potentially other tools too;

  • Set “guest.commands.enable = FALSE“ in the .VMX file
  • Set “guest.commands.enable = FALSE” in the host-wide config file


The following links and books are well worth reading if you have the time;

One thought on “VCAP study notes – section 8.1, PowerCLI

Leave a Reply

Your email address will not be published. Required fields are marked *