Getting Started with PowerCLI 4.1 – Automating Your vSphere Environment

Getting Started with PowerCLI 4.1 – Automating Your vSphere Environment

Welcome PowerCLI Users !

This document contains frequently asked questions about managing VMware vSphere with PowerCLI. This document is a wiki page, so if you have contributions or corrections, feel free to make them by editing the document directly.

Note: If you are using Internet Explorer, the code samples below do not render properly. To deal with this problem you can click "Edit Document" on the left hand side of the page, switch to plain text view, and copy text out of the document.

General vSphere PowerCLI Questions:

Q: What is vSphere PowerCLI ?

A: vSphere PowerCLI is a set of snapins based on Windows PowerShell that provide administration and automation for VMware vSphere. vSphere PowerCLI ships with over 200 commandlets (pre-built commands) to help administrators manage vSphere.

Q: What can you do with vSphere PowerCLI ?

A: vSphere PowerCLI is built on the vSphere API. As a general rule you can do most things with PowerCLI than you can with the vSphere Client. This means that you can script common tasks to help you save time.

Q: What is the latest version of vSphere PowerCLI ?

A: vSphere PowerCLI 4.1 is the latest release.

Q: Where can I get the latest version of vSphere PowerCLI ?

A: vSphere PowerCLI has a centralized website in our communities where users can get the latest downloads, documentation, ask questions in our forums.

Q: Where can I get the PowerCLI Poster ?

A: Online version of the PowerCLI poster can be found on http://vmware.com/go/powercli.

Q: Which client platforms does vSphere PowerCLI support?

A: Windows 7, Windows 2008 Server, Windows Vista, Windows XP, Windows Server 2003

Q: What versions of PowerShell are compatible with the vSphere PowerCLI ?

A: Windows PowerShell 1.0 or Windows PowerShell 2.0 Release To Manufacture (RTM).

Q. I am new to PowerCLI what videos do you recommend we view to learn the basics ?

A. Yavor Boychev from PowerCLI engineering put together some very helpful videos.

Getting Started with PowerCLI http://vimeo.com/15621794

Creating my first Report with PowerCLI: http://vimeo.com/15621466

Q: Is PowerCLI a supported scripting language?

A: Yes.

Q: What type of support is available for PowerCLI?

A: VMware offers organizations Scripting Support when using PowerCLI – http://vmware.com/go/sdksupport. Please visit site for more details on scope of offerings.

Q: What Training is available for PowerCLI ?

A: VMware offers a two day training course for PowerCLI. Customers can use their PSO credits and apply it to course. Course is available worldwide please consult with your local VMware and Partner Training Center – http://vmware.com/go/vsphereautomation

Lets start scripting - Initial Steps

Q: How do I connect to a vCenter Server or ESX host?

A: Use the Connect-VIServer cmdlet and provide a value to the Server parameter.

Connect-VIServer -Server

Q: How can I understand which PowerCLI version currently I have?

A: Use the cmdlet Get-PowerCLIVersion which prints information about the product version:

Get-PowerCLIVersion
PowerCLI Version
----------------
VMware vSphere PowerCLI 4.1 build 264274

General usage questions:

Q: How do I stop PowerShell from prompting me for confirmation before taking action?

A: Using parameter -Confirm one can bypass the confirmation messagebox.

This parameter takes input as a Boolean.

Use

-Confirm:$false

Q: Can I manage more than one vCenter Server at a time? Can I connect to both ESX and vCenter Server at the same time.

A: Yes, there’s nothing special in this scenario.

Connect-VIServer <VC 1>
Connect-VIServer <VC 2>

# Getting all VMs across all vCenter Server hosts.
Get-VM

Q: How can I see all commandlets that PowerCLI has?

A: This can be done by calling Get-VICommand function:

# getting all PowerCLI commandlets
Get-VICommand

# getting all commandlets that manipulates virtual machines
Get-VICommand | ? { $_.Noun -eq 'VM' }

# list all Get commandlets
Get-VICommand | ? { $_.Verb –eq 'Get'}

Q: Is there any help about PowerCLI commandlets?

A: Yes, each PowerCLI commandlet has help. The help is available directly in PowerCLI console. There is also online version of the help.

# Getting the help for Get-VM commandlet
help Get-VM

# Opening the online version of Get-VM commandlet
help Get-VM –online

VM Lifecycle:

Q: How do I create a VM?

A: You can create a new virtual machine using the New-VM cmdlet. Before running this cmdlet, you need to connect to a server. The following examples shows different ways to create new virtual machine:

# creating virtual machine with default values for GuestID, Disk size, Memory size, etc.
New-VM -Name <target vm name>  -Host <host-name> 

# creating virtual machine specifying custom values for machine characteristics
New-VM –Name <target vm name> –Host <host-name> -Datasotre <Name-of-datasore> -DiskMB 20000,50000 –MemoryMB 4096 –NumCPU 2 –GuestID winNetEnterprise64Guest –CD –Description "Win2003Server domain controller"

Q: How do I create a VM on a particular datastore?

A: To create a virtual machine on a particular datastore, we need the reference of the datastore. This script creates a new virtual machine on a particular datastore.

$datastore = Get-Datastore -Name "Select-Datastore-Name"
New-VM -Name "Target-VM" -Host <host-name> -Datastore $datastore

Q: How can I control the power state of virtual machines?

A: There are PowerCLI commandlets for starting, stopping, restarting and suspending virtual machines – Start-VM, Stop-VM, Suspend-VM, Stop-VM. The follow examples show how to use some of them:

# filtering machines by name and start those that are not started
Get-VM <name-filter> | where { $_.PowerState –eq "PoweredOff" } | Start-VM

# stopping virtual machine, defining that we do not want to confirm
# each stop operation
Get-VM <name-filter> | Stop-VM –confirm:$false

Q: Is there a way to stop or restart virtual machine in graceful way?

A: Yes, if the virtual machine has installed VMware Tools in it, it is possible to invoke operations like stop, restart and suspend within the guest OS. The commandlets are Stop-VMGuest, Restart-VMGuest, Shutdown-VMGuest

# Gracefully shut downing all machines which name starts with WinXP string. 
Get-VM WinXP* | Shutdown-VMGuest –confirm:$false

Q: I need to upgrade memory of all virtual machines under given folder/resource pool, how can I do it?

A: There is PowerCLI commandlet named Set-VM which allows to change a lot of virtual machines characteristics like name, description, memory size, number of CPU, etc. The following example shows how to filter virtual machines by resource pool and to update their memory to 2 GB.

# Getting all virtual machines under given resource pool and upgrade their memory to 2048 MB
Get-ResourcePool <resource pool name> | Get-VM | Set-VM –MemoryMB 2048 –confirm:$false

Q: How can I import (register) an existing VM?

A: This script imports a VM into the vm folder.

New-VM –Name <Target-VM-Name> –VMFilePath "\[<Datastore Name>\] <Path To VMX>.vmx" –VMHost <host-name>

Q: How can I set VM power-on options, such as configuring tools to automatically upgrade?

A: By setting the ToolsUpgradePolicy property to upgradeAtPowerCycle. With this setting Tools upgrade is automatically performed on the virtual machine and rebooted if necessary. This scenario is demonstrated by the following script.

$vm = Get-VM VMName | Get-View 
$vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec
$vmConfigSpec.Tools = New-Object VMware.Vim.ToolsConfigInfo 
$vmConfigSpec.Tools.ToolsUpgradePolicy = "UpgradeAtPowerCycle"
$vm.ReconfigVM($vmConfigSpec)

Q: How do I set resources, such as limits and reservations, on a VM?

A: There’s Set-VMResourceConfiguration cmdlet that allows changing of CPU and memory reservation, limit and level for each virtual machine

$vm = Get-VM VMName | Get-VMResourceConfiguration | Set-VMResourceConfiguration –CPUSharesLevel “High”

Q: How can I determine the version of VMware Tools my VMs are using?

A: This information is contained in the Toolversion property under the config property of the VirtualMachine object. To get this information, use the following script.

Get-VM VMName | get-view | select Name, @{ Name="ToolsVersion"; Expression={$_.config.tools.toolsVersion}}

Q: How can I change a VM's IP address?

A: To change the IP setting, use the following script.

Get-VM VMName | Get-VMGuestNetworkInterface -GuestUser Administrator -GuestPassword <password> -HostUser root -HostPassword <password> | Set-VMGuestNetworkInterface -IPPolicy Static -Ip <IPAddress> -Netmask 255.255.252.0 -Gateway <Gateway> -GuestUser Administrator -GuestPassword <password> -HostUser root -HostPassword <password> 

Q: How do I VMotion a VM?

A: The following script demonstrates how to VMotion a VM to a desired VM Host.

Get-VM <target-vm> | Move-VM -Destination <name-of-destination-host>

Q: How do I delete or unregister virtual machine?

A: There is commandlet named Remove-VM which allows two things – to remove virtual machine from inventory and its contents from datastore and just to unregister virtual machine from the inventory. The following examples show both actions:

# Unregistering virtual machine from inventory
Get-VM <vm name> | Remove-VM –confirm:$false

# Delete virtual machine from inventory and its contents from datastore
Get-VM <vm name> | Remove-VM –DeleteFromDisk –confirm:$false

Q: How can I determine the connection state of CD ROM drives and floppy drives?

A: The connection state of CD drives and Floppy drives can be determined by the property “Connected:”. This returns Boolean value $true for connected and $false for disconnected state. The following script determines the connection state of CD and floppy drive.

Write-Output "FloppyDrive Status:"
Get-VM | Get-FloppyDrive | select @{'n' = 'Name'; 'e' = { $_.Parent.Name} }, @{'n' = 'IsConnected'; 'e' = {$_.ConnectionState.Connected}}

Write-Output "CDDrive Status:"
get-vm | Get-CDDrive | select @{'n' = 'Name'; 'e' = { $_.Parent.Name} }, @{'n' = 'IsConnected'; 'e' = {$_.ConnectionState.Connected}}

Distribution of virtual machines

Q: I have set up different virtual machine templates, how can I deploy virtual machines from them?

A: The commandlet New-VM allows deploying virtual machine from existing template.

Get-Template WindowsXPTemplate | New-VM –Name <target-vm-name> -VMHost <name of vmhost> -Datastore <name of datastore>

Q: I want to duplicate an existing virtual machine, how can I do that?

A: The commandlet New-VM allows to clone virtual machine from other existing virtual machine.

New-VM –VM <name of existing VM> -Name <target-vm-name> -VMHost <name of vmhost> -Datastore <name of datastore>

Q: Is it possible to apply customization specification while virtual machine is being deployed from template?

A: Yes, PowerCLI has set of commandlets to obtain, change and create customization specifications. PowerCLI also allows applying customization specification along with the deployment by using the New-VM commandlet.

$spec = Get-OSCustomizationSpec –Name <spec name>
Get-Template <template name> | New-VM –Name <target-vm-name> -VMHost <name of vmhost> -Datastore <name of datastore> -OSCustomizationSpec $spec

Snapshots:

Q: How do I snapshot a VM? Multiple VMs?

A: Use the New-Snapshot cmdlet to create a snapshot of a virtual machine. The following script creates a snapshot named “Target-Snapshot” for all virtual machines.

To do snapshot of a particular machine use the –VM parameter and specify the virtual machine name.

Get-VM | New-Snapshot -Name ”Target-Snapshot”
# or
New-Snapshot –Name “Target-Snapshot” –VM myVM

Q: How do I revert a VM to a particular snapshot?

A: A virtual machine can have multiple snapshots and you can revert the VM to any of them at a time. The following script reverts a virtual machine to a specified snapshot.

$snapshot = Get-Snapshot –VM myVM –Name ”Target-Snapshot”
Set-VM –VM myVM –Snapshot $snapshot

Q: How can I identify all snapshots older than a particular date?

A: The following script lists snapshots that are older than 30 days.

Get-VM | Get-Snapshot | Where { $_.Created -lt (Get-Date).AddDays(-30)} | select Name, Created

Datastores

Q: Is it possible to browse a datastore contents?

A: Yes, PowerCLI gives this ability based on the Powershell provider concept. This mean that VMware datastores can be browsed with the native Powershell commandlets like Set-Location, Get-Item, Get-ChildItem and their aliases like cd, ls, dir. PowerCLI datastore provider also allows to manipulate datastore contents with native Powershell commandlets like Copy-Item, Move-Item, Remove-Item, etc.

After PowerCLI starts there is registered drive vmstores: which contains a sub folder for each currently connected server. See the following example that shows some basic operations with vmstores drive:

# this example will list all files and subfolders that starts with WinXP
# inside the datastore with name Storage1.
ls vmstores:\myServer@443\Datacenter\Storage1\WinXP*

# this example shows how to delete all log files inside sub-folder Machine1
rm vmstores:\myServer@443\Datacenter\Storage1\Machine1\*.log

Q: Is it possible to copy files from/to datastores?

A: Yes it is possible to copy files from/to datastore using the commandlet Copy-DatastoreItem.

# downloading a virtual machine on local workstation
Copy-DatastoreItem vmstores:\myServer@443\Datacenter\Storage1\WindowsVM1\* d:\VirtualMachines\WindowsVM1\

# uplading ISO image on datastore
Copy-DatastoreItem d:\IsoImages\UbuntoDesktop.iso vmstores:\myServer@443\Datacenter\Storage1\IsoImages\

ESX Host Configuration:

Q: How can I create virtual switches and portgroups?

A: The following script creates virtual switches.

Get-VMHost YOURHOST | New-VirtualSwitch -name "My New Switch" -nic YOURNIC (e.g. vmnic1)
Get-VMHost YOURHOST | Get-VirtualSwitch -name "My New Switch" | New-VirtualPortGroup -vlanid 100

Q: How can I configure NTP?

A: The following script configures the NTP.

Add-VMHostNtpServer –VMHost YOURHOST –NtpServer "<Your NTP Server>"
Set-VMHost –VMHost YOURHOST –TimeZone "<Your Timezone>"

Q: How can I rescan Host Bus Adapters (HBAs)?

A: The following script rescans Host Bus Adapters (HBAs).

Get-VMHost | Get-VMHostStorage -RescanAllHBA

Q: How can I display and configure the physical adapters of my ESX host?

A: The following script displays a list of the physical adapters of an ESX host.

Get-VMHost | Get-VMHostNetworkAdapter –Physical | %{Write-Host $_.VMHost.Name, $_.Name} 

The following script configures the physical adapters of ESX host.

Get-VMHost | Get-VMHostNetworkAdapter –Physical –Name "NIC_TO_CONFIGURE" | Set-VMHostNetworkAdapter -duplex full -bitratepersecmb 100

Q: How can I power off an ESX host?

A: The following script powers off an ESX host.

Stop-VMHost –VMHost YOURHOST

Reporting

Q: How can I create a tabular report of all my VMs, including their configurations and number of virtual disks that they have?

A: The following script creates a tabular report of all VMs with their configurations.

Get-VM | Select-Object Name, MemoryMB , @{ Name="MemReservation"; Expression={$_.ExtensionData.Summary.Config.memoryReservation}} , @{ Name="numCpu"; Expression={$_.ExtensionData.Summary.Config.numCpu}} , @{ Name="numVirtualDisks"; Expression={$_.ExtensionData.Summary.Config.numVirtualDisks}} | Format-Table

# This output can be redirected to Export-Csv which will produce a CSV file 
Get-VM | Select-Object Name, MemoryMB , @{ Name="MemReservation"; Expression={$_.ExtensionData.Summary.Config.memoryReservation}} , @{ Name="numCpu"; Expression={$_.ExtensionData.Summary.Config.numCpu}} , @{ Name="numVirtualDisks"; Expression={$_.ExtensionData.Summary.Config.numVirtualDisks}} | Export-Csv VMConfiguration.csv -NoTypeInformation

Q: I want report that shows the capacity and free space of all available datastores, is it possible?

A: Yes, this can be done easier with Get-Datastore commandlet.

# This example displays the required information on the screen
Get-Datastore | select Name,CapacityMB,FreeSpaceMB | Format-Table –AutoSize

# This example exports the same report into CSV file
Get-Datastore | select Name,CapacityMB,FreeSpaceMB | Export-CSV datastoreInformation.csv -NoTypeInformation

Q: I want report for provisioned and used space by virtual machines, is it possible?

A: Yes, VirtualMachine object has properties UsedSpaceGB and ProvisionedSpaceGB, so using the Get-VM made easier this report creation.

# Exporting information for used and provisioned space by virtual machine
# in CSV file
Get-VM | Select Name,UsedSpaceGB,ProvisionedSpaceGB | Export-Csv vmSpaceReport.csv -NoTypeInformation

Q: I want report about all VM Hosts, their parent cluster, CPU count, and available memory, is it possible?

A: Yes , you can use Get-VMHost like this:

Get-VMHost | select Name,@{'n' = 'ParentCluster'; 'e' = { $_.Name } }, NumCPU,CpuTotalMhz,MemoryTotalMB,ProcessorType | Export-CSV vmhostReport.csv -NoTypeInformation

Guest OS interaction

Q: Is it possible to start process inside virtual machine?

A: Yes, if the virtual machine has installed VMware Tools it is possible to invoke batch file or powershell script on Windows guest OS and bash scripts on Linux guest OS. This is possible with Invoke-VMScript commandlet.

# Calling simple dir command against Windows guest
Invoke-VMScript –VM <vm-name> -ScriptText 'dir c:\' -GuestUser <guest user> -GuestPassword <guest password> -HostUser <host user> -HostPassword <host password> 

Q: Is it possible to copy file from/to virtual machine?

A: Yes, if the virtual machine has installed VMware Tools it is possible to copy from and to guest OS files using the Copy-VMGuestFile commandlet.

# copy a file from local workstation into windows guest
Copy-VMGuestFile –LocalToGuest –Source c:\scripts\myScript.ps1 –Destination c:\scripts\ -VM <vm-name> -GuestUser <guest user> -GuestPassword <guest password> -HostUser <host user> -HostPassword <host password> 

Q: I have a lot of virtual machines that need VMware tools upgrade. Is it possible to do that with PowerCLI?

A: Yes, it is possible by using Update-Tools commandlet.

Get-VM | ? { $_.ExtensionData.Guest.ToolsStatus -eq 'toolsOld' } | Update-Tools

Managing VM Hosts, clusters and resource pools

Q: How can I add a host to existing cluster?

A: This task can be completed in two ways. It should be used Add-VMHost if the VM Host is not included in inventory and Move-VMHost when the VM host already is connected to the vSphere Virtual Center.

# adding host to inventory directly in existing cluster
$cluster = Get-Cluster <target-cluster-name>
Add-VMHost –Name <name-of-cluster> -Location $cluster –User <host user> -Password <host password> -Force

# moving the host to the target cluster
$cluster = Get-Cluster <target-cluster-name>
Get-VMHost <vmhost-name> | Move-VMHost –Destination $cluster –confirm:$false

Q: I want to perform some maintenance operations on one of my hosts, what should I do?

A: First the host should be put in maintenance mode. If the host is inside DRS cluster all powered on virtual machines will be migrated to another to another host.

Set-VMHost -VMHost <host name> -State Maintenance

Q: I want to create resource pool with specific memory and CPU reservations and limits, how can I do that?

A: Using New-ResourcePool it is possible to create a resource pool with desired parameters. Using Set-ResourcePool it is possible to update parameters of existing resource pool.

New-ResourcePool -Name <resource pool name> -Location <Parent Cluster name or VMHost name or Resource pool> -CpuReservationMhz 4000  -MemReservationMB 4000

Other:

Q: How can I create folders that appear under "Virtual Machines and Templates" in VC (a so-called "Blue Folder")?

A: A "Blue Folder" is a folder created under the VM folder. For example:

Get-Folder vm | New-Folder -Name ”Target-Folder-Name”

Q: I'm concerned about the security implications of Invoke-VMScript, how can I disable it?

A: Invoke-VMscript can be disabled on a VM-by-VM basis by adding this line to the VM's VMX file: monitor_control.restrict_backdoor = "true" . You can add this line by hand or you can add it with the following script:

$vmsToDisableInvoke = Get-VM <vms to reconfigure>
$vmsToDisableInvoke | foreach {
 $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec
 $vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue
 $vmConfigSpec.extraconfig[0].Key="monitor_control.restrict_backdoor"
 $vmConfigSpec.extraconfig[0].Value="true"
 $_.ExtensionData.ReconfigVM($vmConfigSpec)
}

Please help us help our community - Add the questions you often get asked by your peers and tired of having to answer it many times.

Comments

As a new PowerCLI user I found this document to be very helpful. Thank you.

.

Agreed - very helpful.  But what in the world does the @ represent?  I took a regular Powershell class and didn't see it come up anywhere.

Hi, It's Hashtable. N and E's Name & Expression in the hashtable

For example:

@{'n' = 'Name'; 'e' = { $_.Parent.Name} }
Mostly it used in select, instead showing the title name as $_.Parent.Name - it's been converted to Name.
Version history
Revision #:
1 of 1
Last update:
‎09-28-2010 04:21 PM
Updated by: