VMware/PowerCLI
PowerCLI
VMware PowerCLI - http://www.vmware.com/go/powercli
- "VMware vSphere PowerCLI is a powerful command line tool that lets you automate all aspects of vSphere management, including network, storage, VM, guest OS and more. PowerCLI is distributed as a Windows PowerShell snapin, and includes more than 250 PowerShell cmdlets, along with documentation and samples." [1]
Welcome to the VMware vSphere PowerCLI! Log in to a vCenter Server or ESX host: Connect-VIServer To find out what commands are available, type: Get-VICommand To show searchable help for all PowerCLI commands: Get-PowerCLIHelp Once you've connected, display all virtual machines: Get-VM If you need more help, visit the PowerCLI community: Get-PowerCLICommunity
NOTE: VMware PowerCLI requires Windows PowerShell 2.0.
Documentation
VMware APIs and SDKs Documentation - http://www.vmware.com/support/pubs/sdk_pubs.html
VMware vSphere PowerCLI - http://www.vmware.com/support/developer/PowerCLI/index.html
- Release Notes
- Installation Guide
- Administration Guide(Updated 1/13/2011)
- Developer's Guide
- Online Cmdlet Reference
Online Cmdlet Reference - http://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/html/index.html
Quick Reference Poster
Quick Reference Poster [2]
Help
To show searchable help for all PowerCLI commands:
Get-PowerCLIHelp
To find out what commands are available, type:
Get-VICommand
Help on command:
get-help [command]
Connect
Log in to a vCenter Server or ESX host: Connect-VIServer
SYNTAX
Connect-VIServer [[-Server] <String[]>] [-Port <Int32>] [-Protocol <String> ] [-Credential <PSCredential>] [-User <String>] [-Password <String>] [-Sess ion <String>] [-NotDefault] [-SaveCredentials] [<CommonParameters>]
Connect-VIServer -Menu [<CommonParameters>]
Connect:
C:\PS> Connect-VIServer -Server 10.23.112.235 -Protocol https -User admin -Password pass C:\> Connect-VIServer -Server vc C:\> Connect-VIServer -Server vc -User root -Password Password1
Help:
get-help connect-viserver
Examples:
get-help connect-viserver -examples
VM Management
List VMs
Get-VM: http://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/html/Get-VM.html
[vSphere PowerCLI] C:\> Get-VM Name PowerState Num CPUs Memory (MB) ---- ---------- -------- ----------- win245 PoweredOn 1 1024 TESTr2 PoweredOn 1 4096
List all available columns:
get-vm | select *
Select specific columns:
get-vm | select Name,VMHost
Filter by name:
get-vm -name test111 get-vm | select Name | Where-Object {$_.Name -like "*test*"}
List VMDKs associated with VM:
get-vm | where-object {$_.name -like "*test*"} | get-harddisk
get-vm -name test333 | Add-Member -MemberType ScriptProperty -Name 'VMXPath' -Value {$this.extensiondata.config.files.vmpathname} -Passthru -Force | select name,vmxpath Get-VM -name test333 | Select Name, @{N="VMX";E={$_.Extensiondata.Summary.Config.VmPathName}}
Export VM info to Excel
Get-VM | Select-Object Name,NumCPU,MemoryMB,PowerState,VMHost | Export-CSV VMs.csv -NoTypeInformation
Source: 10 Steps to Kick-Start Your VMware Automation with PowerCLI
List Powered On VMs
Get-VM | Where-Object { $_.PowerState -eq "PoweredOn" } | Select-Object Name
Source: 10 Steps to Kick-Start Your VMware Automation with PowerCLI
List VMs with Connected CD Drives
Get-VM | Where-Object {$_ | Get-CDDrive | Where-Object { $_.ConnectionState.Connected -eq "true" } } | Select-Object Name
Source: 10 Steps to Kick-Start Your VMware Automation with PowerCLI
Remove VM
Remove-VM [-DeletePermanently] -Confirm:$false "[VMNAME]"
Scripting
Comments
# this is a comment
Variables
$var = 1 $var = "test" echo $var
Write Message
write-host "message"
All Commands
Name ---- Add-PassthroughDevice Add-VMHost Add-VmHostNtpServer Apply-DrsRecommendation Apply-VMHostProfile Connect-VIServer Copy-DatastoreItem Copy-HardDisk Copy-VMGuestFile Disconnect-VIServer Dismount-Tools Export-VApp Export-VMHostProfile Format-VMHostDiskPartition Get-AdvancedSetting Get-AlarmAction Get-AlarmActionTrigger Get-AlarmDefinition Get-Annotation Get-CDDrive Get-Cluster Get-CustomAttribute Get-Datacenter Get-Datastore Get-DrsRecommendation Get-DrsRule Get-ErrorReport Get-EsxCli Get-EsxTop Get-FloppyDrive Get-Folder Get-HAPrimaryVMHost Get-HardDisk Get-Inventory Get-IScsiHbaTarget Get-Log Get-LogType Get-NetworkAdapter Get-NicTeamingPolicy Get-OSCustomizationNicMapping Get-OSCustomizationSpec Get-PassthroughDevice Get-PowerCLIConfiguration Get-PowerCLIVersion Get-ResourcePool Get-ScsiController Get-ScsiLun Get-ScsiLunPath Get-Snapshot Get-Stat Get-StatInterval Get-StatType Get-Task Get-Template Get-UsbDevice Get-VApp Get-VICredentialStoreItem Get-VIEvent Get-View Get-VIObjectByVIView Get-VIPermission Get-VIPrivilege Get-VIRole Get-VirtualPortGroup Get-VirtualSwitch Get-VM Get-VMGuest Get-VMGuestNetworkInterface Get-VMGuestRoute Get-VMHost Get-VMHostAccount Get-VMHostAdvancedConfiguration Get-VMHostAvailableTimeZone Get-VMHostDiagnosticPartition Get-VMHostDisk Get-VMHostDiskPartition Get-VMHostFirewallDefaultPolicy Get-VMHostFirewallException Get-VMHostFirmware Get-VMHostHba Get-VMHostModule Get-VMHostNetwork Get-VMHostNetworkAdapter Get-VMHostNtpServer Get-VMHostPatch Get-VMHostProfile Get-VMHostRoute Get-VMHostService Get-VMHostSnmp Get-VMHostStartPolicy Get-VMHostStorage Get-VMHostSysLogServer Get-VMQuestion Get-VMResourceConfiguration Get-VMStartPolicy Import-VApp Import-VMHostProfile Install-VMHostPatch Invoke-VMScript Mount-Tools Move-Cluster Move-Datacenter Move-Folder Move-Inventory Move-ResourcePool Move-Template Move-VM Move-VMHost New-AdvancedSetting New-AlarmAction New-AlarmActionTrigger New-CDDrive New-Cluster New-CustomAttribute New-CustomField New-Datacenter New-Datastore New-DrsRule New-FloppyDrive New-Folder New-HardDisk New-IScsiHbaTarget New-NetworkAdapter New-OSCustomizationNicMapping New-OSCustomizationSpec New-ResourcePool New-ScsiController New-Snapshot New-StatInterval New-Template New-VApp New-VICredentialStoreItem New-VIPermission New-VIProperty New-VIRole New-VirtualPortGroup New-VirtualSwitch New-VM New-VMGuestRoute New-VMHostAccount New-VMHostNetworkAdapter New-VMHostProfile New-VMHostRoute Remove-AdvancedSetting Remove-AlarmAction Remove-AlarmActionTrigger Remove-CDDrive Remove-Cluster Remove-CustomAttribute Remove-CustomField Remove-Datacenter Remove-Datastore Remove-DrsRule Remove-FloppyDrive Remove-Folder Remove-HardDisk Remove-Inventory Remove-IScsiHbaTarget Remove-NetworkAdapter Remove-OSCustomizationNicMapping Remove-OSCustomizationSpec Remove-PassthroughDevice Remove-ResourcePool Remove-Snapshot Remove-StatInterval Remove-Template Remove-UsbDevice Remove-VApp Remove-VICredentialStoreItem Remove-VIPermission Remove-VIProperty Remove-VIRole Remove-VirtualPortGroup Remove-VirtualSwitch Remove-VM Remove-VMGuestRoute Remove-VMHost Remove-VMHostAccount Remove-VMHostNetworkAdapter Remove-VMHostNtpServer Remove-VMHostProfile Remove-VMHostRoute Restart-VM Restart-VMGuest Restart-VMHost Restart-VMHostService Set-AdvancedSetting Set-AlarmDefinition Set-Annotation Set-CDDrive Set-Cluster Set-CustomAttribute Set-CustomField Set-Datacenter Set-Datastore Set-DrsRule Set-FloppyDrive Set-Folder Set-HardDisk Set-IScsiHbaTarget Set-NetworkAdapter Set-NicTeamingPolicy Set-OSCustomizationNicMapping Set-OSCustomizationSpec Set-PowerCLIConfiguration Set-ResourcePool Set-ScsiController Set-ScsiLun Set-ScsiLunPath Set-Snapshot Set-StatInterval Set-Template Set-VApp Set-VIPermission Set-VIRole Set-VirtualPortGroup Set-VirtualSwitch Set-VM Set-VMGuestNetworkInterface Set-VMHost Set-VMHostAccount Set-VMHostAdvancedConfiguration Set-VMHostDiagnosticPartition Set-VMHostFirewallDefaultPolicy Set-VMHostFirewallException Set-VMHostFirmware Set-VMHostHba Set-VMHostModule Set-VMHostNetwork Set-VMHostNetworkAdapter Set-VMHostProfile Set-VMHostRoute Set-VMHostService Set-VMHostSnmp Set-VMHostStartPolicy Set-VMHostStorage Set-VMHostSysLogServer Set-VMQuestion Set-VMResourceConfiguration Set-VMStartPolicy Shutdown-VMGuest Start-VApp Start-VM Start-VMHost Start-VMHostService Stop-Task Stop-VApp Stop-VM Stop-VMHost Stop-VMHostService Suspend-VM Suspend-VMGuest Suspend-VMHost Test-VMHostProfileCompliance Test-VMHostSnmp Update-Tools Wait-Task Wait-Tools
.NET
"VMware vSphere PowerCLI provides a Windows PowerShell interface to the vSphere API. vSphere PowerCLI includes PowerShell Cmdlets (pronounced, “command-lets”) for administering vSphere components. In addition, the vSphere PowerCLI package includes the vSphere SDK for .NET for developers who want to create their own applications." [5]
vSphere SDK for .NET Developer’s Guide http://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/doc/viwin_devg.pdf
vSphere SDK for .NET Developer’s Guide
See VMware .NET SDK
Host Object
$hostobj = Get-VMHost $host
$hostobj.[tab completion]
Wirey.com » Blog Archive » Patching ESX(i) using PowerCLI - http://wirey.com/2010/03/patching-esxi-using-powercli/
$hostobj | get-view -Property Name,Config.Product | select Name,{$_.Config.Product.Fullname} #Check current build numbers
Name $_.Config.Product.Fullname ---- -------------------------- 216.119.199.245 VMware ESXi 4.0.0 build-208167
Move vms:
$hostobj1 | get-vm | move-vm -destination ($vmhostobj2)
#Reboot the ESX Server host 1 $VMhostObj1 | Restart-VMHost -Confirm:$false Write-Host "Waiting 2.5 minutes for $host1 to reboot" Sleep 150
################################################################## # ROBO Cluster patching script by Rob Upham - r o b @ vmware.com # # Script assumes a two-node cluster with vMotion but no DRS # ################################################################## ########################################## # Edit these values to suit your cluster # # and the patch being applied # ########################################## $VC = "robo-vc-x64.vmwdemo.com" $host1 = "esx-robo-1.vmwdemo.com" $host2 = "esx-robo-2.vmwdemo.com" $patchpath = "/vmfs/volumes/Template-FC-EMC/Patches/ESXi400-201002001/metadata.zip" #Patch bundles should be unzipped, placed on shared VMFS or NFS storage and the metadata.zip file referenced above # e.g. $patchpath = "/vmfs/volumes/NFS-Vol1/Patches/ESXi400-200912001/metadata.zip" ######################## # Work gets done below # ######################## #Connect to vCenter Server Write-Host "Connecting to vCenter Server" Connect-VIServer -Server $VC #Get host objects $VMHostObj1 = Get-VMHost $Host1 $VMHostObj2 = Get-VMHost $Host2 #Check current build numbers Write-Host "Hosts to be patched are:" Write-Host "Host1 = $host1" $VMHostObj1 | get-view -Property Name,Config.Product | select Name,{$_.Config.Product.Fullname} Write-Host "Host2 = $host2" $VMHostObj2 | get-view -Property Name,Config.Product | select Name,{$_.Config.Product.Fullname} #Host 1 #Move vms to Host 2 and enable maintenance mode Write-Host "Moving VMs from $host1 to $host2" $VMHostObj1 | get-vm | move-vm -destination ($VMHostObj2) Write-Host "$host1 entering maintenance mode" $VMHostObj1 | set-vmhost –state maintenance #Update host 1 Write-Host "Patching $host1 with patch $patchpath" $VMHostObj1 | Install-VMHostPatch -HostPath $patchpath #Reboot the ESX Server host 1 $VMhostObj1 | Restart-VMHost -Confirm:$false Write-Host "Waiting 2.5 minutes for $host1 to reboot" Sleep 150 $VMHostState = (Get-VMHost -Name $host1 -ErrorAction SilentlyContinue).State While ($VMHostState -eq "NotResponding"){ Write-Host "ESX Server state is" $VMHostState Write-Host "Waiting 20 seconds until ESX Server starts responding" sleep 20 $VMHostState = (Get-VMHost -Name $host1).State } Write-Host "Taking ESX Server host out of Maintenance Mode" $VMHostObj1 | set-vmhost –state connected Write-Host "Patching $host1 complete" #Host 2 #Move vms to Host 1 and enable maintenance mode Write-Host "Moving VMs from $host2 to $host1" $VMHostObj2 | get-vm | move-vm -destination ($VMHostObj1) Write-Host "$host2 entering maintenance mode" $VMHostObj2 | set-vmhost –state maintenance #Update host 2 Write-Host "Patching $host2 with patch $patchpath" $VMHostObj2 | Install-VMHostPatch -HostPath $patchpath #Reboot the ESX Server host 2 $VMhostObj2 | Restart-VMHost -Confirm:$false Write-Host "Waiting 2.5 minutes for $host2 to reboot" Sleep 150 $VMHostState = (Get-VMHost -Name $host2 -ErrorAction SilentlyContinue).State While ($VMHostState -eq "NotResponding"){ Write-Host "ESX Server state is" $VMHostState Write-Host "Waiting 20 seconds until ESX Server starts responding" sleep 20 $VMHostState = (Get-VMHost -Name $host2).State } Write-Host "Taking ESX Server host out of Maintenance Mode" $VMHostObj2 | set-vmhost –state connected Write-Host "Patching $host2 complete" Write-Host "Build numbers are now as follows:" $VMHostObj1 | get-view -Property Name,Config.Product | select Name,{$_.Config.Product.Fullname} $VMHostObj2 | get-view -Property Name,Config.Product | select Name,{$_.Config.Product.Fullname} Write-Host "All patching complete"
vCenter Update Manager PowerCLI
# vCenter Update Manager PowerCLI # http://communities.vmware.com/community/vmtn/server/vsphere/automationtools/powercli/updatemanager # VMware vSphere Update Manager PowerCLI Documentation # http://www.vmware.com/support/developer/ps-libs/vumps/ # VMware vSphere Update Manager PowerCLI Installation and Administration Guide Update Manager PowerCLI 5.1 # http://pubs.vmware.com/vsphere-51/topic/com.vmware.ICbase/PDF/vsphere-update-manager-powercli-51-inst-admg.pdf --- Import patches, the hard way: # VMware Communities: Import host patches into Update Manager # http://communities.vmware.com/docs/DOC-15885 # VMware Communities: Import host upgrade into Update Manager # http://communities.vmware.com/docs/DOC-15886 --- $vi_server = connect-viserver -server vum.oeey.com -user root -password Password1 $esx_hosts = $vi_inventory | where-object {$_.name.startswith('vum-esx')} $esx_hosts = Get-VMHost $scan_result = $esx_hosts | scan-inventory # returns false if one of the entities did not scan correctly $baselines = get-baseline | where-object {$_.name -eq 'fusionio'} --- # connect to vcenter server $vi_server while ($true) { $vi_server = connect-viserver -server vum.oeey.com -user root -password Password1 if ($? -eq $true) { break } echo "." sleep 10 } # get hosts $esx_hosts = Get-VMHost # verify scan foreach ($esx in $esx_hosts) { $esx | Scan-Inventory if ($? -ne $true) { # restart esx host $esx | restart-vmhost -confirm:$false -force sleep 30 while ($true) { sleep 10 echo "retrying..." $esx | Scan-Inventory if ($? -eq $true) { break } } } } --- esx server management --- # restart esx host $esx_host | restart-vmhost -confirm:$false -force # get host states (should be: HOSTNAME, Connected, Connected) Get-VMHost | Select Name, State, ConnectionState # get esx host IP: # note: Get-View gets all columns Get-VMHost | Get-View | Select {$_.Summary.ManagementServerIP } --- # target entity - in this case a folder $TARGET = "ESX" # download patches from repo $patches = Download-Patch if ( $? -ne $true ) { echo "No Patches Failure" ; exit 1 } if ($patches.count > 0) { echo "Patches found" } # get patches - from patch list $extentions = Get-Patch -BundleType Extension if ( $? -ne $true ) { echo "Extension Failure" ; exit 1 } # create baseline from patches $baseline = New-PatchBaseline -Static -Name "fusionio" -Extension -IncludePatch $extentions if ( $? -ne $true ) { echo "Baseline Failure" ; exit 1 } # attach baseline Attach-Baseline -Baseline $baseline -Entity $TARGET if ( $? -ne $true ) { echo "Attach Failure" ; exit 1 } # scan servers Scan-Inventory -Entity $TARGET if ( $? -ne $true ) { echo "Scan Failure" ; exit 1 } # get compliance $compliance = Get-Compliance -Entity $TARGET -ComplianceStatus Unknown if ( $? -ne $true ) { echo "Compliance Failure" ; exit 1 } if ($compliance.count -gt 0) { echo "Compliance Count Failure" ; exit 1 } # get all baselines for target, maybe more than one $baselines = Get-Baseline -Entity $TARGET if ( $? -ne $true ) { echo "Baseline Get Failure" ; exit 1 } # remediate hosts Remediate-Inventory -Entity $TARGET -Baseline $baselines if ( $? -ne $true ) { echo "Remediate Failure" ; exit 1 }
Sample Scripts
APPLE-1078 - Building Custom Image
Add-EsxSoftwareDepot -DepotUrl http://yum-repo.geo.apple.com/vmw/VMware-ESXi-5.1.0-799733-depot Add-EsxSoftwareDepot -DepotUrl http://vibsdepot.hp.com/hpq/sep2012/index.xml Add-EsxSoftwareDepot -DepotUrl http://yum-repo.geo.apple.com/vmw/MLNX-OFED-ESX-1.8.0.1 Add-EsxSoftwareDepot -DepotUrl http://yum-repo.geo.apple.com/vmw/iomemory-vsl-5X-3.1.5.126-offline_bundle-750032 Add-EsxSoftwareDepot -DepotUrl http://yum-repo.geo.apple.com/vmw/Fusion-IO_libvsl-offline-bundle-3.1.5 Add-EsxSoftwareDepot -DepotUrl http://yum-repo.geo.apple.com/vmw/fusionio-cimprovider-esxi5-bundle-3.1.20-119 $op = (Get-EsxImageProfile -Name "ESXi*-standard").Name echo "Using base image profile: $op" $pkgs = Get-EsxSoftwarePackage -Newest $np = New-EsxImageProfile -CloneProfile "$op" -Name "Geo_1_ESXi51_vmw-799733" -Vendor "GeoOps" -SoftwarePackage $pkgs Export-EsxImageProfile -ImageProfile ($np).Name -ExportToBundle -NoSignatureCheck -FilePath c:\img\Geo_1_ESXi51_vmw-799733.zip Export-EsxImageProfile -ImageProfile ($np).Name -ExportToIso -NoSignatureCheck -FilePath c:\img\Geo_1_ESXi51_vmw-799733.iso
Issues
PowerShell 1.0 is not supported
Error:
WARNING: You are running PowerShell version 1.0. PowerShell 1.0 is not be supported by vSphere PowerCLI. Please update you PowerShell to version 2.0
Solution:
- VMware PowerCLI requires Windows PowerShell 2.0.
The term not recognized as a cmdlet
Trying to run the PowerCLI commands from a PowerShell window causes this error:
PS C:\Documents and Settings\kenneth> add-esxsoftwaredepot The term 'add-esxsoftwaredepot' is not recognized as a cmdlet, function, operable program, or script file. Verify the t erm and try again. At line:1 char:20 + add-esxsoftwaredepot <<<<
Cause:
- Do you have PowerCLI running and are you running from the PowerCLI shell?
Solution:
- Install PowerCLI
---
Cause:
- Running from PowerShell window
Solution:
- Need to initialize the PowerCLI environment
. "C:\Program Files\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1"
Execution is disabled
File C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Init ialize-PowerCLIEnvironment.ps1 cannot be loaded because the execution of script s is disabled on this system. Please see "get-help about_signing" for more deta ils. At line:1 char:2 + . <<<< "C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Script s\Initialize-PowerCLIEnvironment.ps1" + CategoryInfo : NotSpecified: (:) [], PSSecurityException + FullyQualifiedErrorId : RuntimeException
Cause:
- When you first installed PowerCLI, it told you:
- "The PowerShell execution policy of this computer is not set to "RemoteSigned". This prevents execution of PowerShell scripts on your computer and will result in erros when VMware vSphere PowerCLI is invoked. It is recommended that you set the execution policy to "RemoteSigned" in order to be able to execute scripts. This can be done by invoking the command 'Set-ExecutionPolicy RemoteSigned' from a PowerShell prompt. - Do this for me"
Solution:
- Click the 'Do this for me' when you installed PowerCLI.
- Set execution policy with 'Set-ExecutionPolicy RemoteSigned'
See current policy:
get-executionpolicy
Set RemoteSigned execution policy:
Set-ExecutionPolicy RemoteSigned
---
An overview of the policy levels:
- Restricted
- Individual cmdlets can run, but not saved Powershell scripts. This is the default setting.
- AllSigned
- Scripts can run, but must have a digital signature even if written on the local computer. Prompts you before running scripts from trusted publishers.
- RemoteSigned
- Scripts written on the local computer do not need a digital signature, but any script downloaded from outside (email, IM, Internet) must have a signature to execute.
- Unrestricted
- Any script can run, but scripts downloaded from outside will run with a warning.
To change the Execution Policy to Unrestricted, type the following command in Powershell
Set-ExecutionPolicy Unrestricted
To change the Execution Policy to RemoteSigned (to run your own scripts), type the following command in Powershell (preferred)
Set-ExecutionPolicy RemoteSigned
fault.RestrictedVersion.summary
fault.RestrictedVersion.summary with ESXi
Stop-VM : 3/8/2011 12:57:40 PM Stop-VM fault.RestrictedVersion.summary At line:1 char:8 + stop-vm <<<< -vm win245 + CategoryInfo : NotSpecified: (:) [Stop-VM], SecurityError + FullyQualifiedErrorId : Client20_MoServiceImpl_Invoke_ViError,VMware.VimAutomation.ViCore.Cm dlets.Commands.StopVM
Solution:
- ESXi is not licensed to use remote features.
- "There are two basic versions of ESXi "free" and "licensed", the scripting toolkits are limited to read-only access for the free version of VMware ESXi. When the host is upgraded to vSphere Essentials, vSphere Essential Plus, vSphere Standard, vSphere Advanced, vSphere Enterprise, or vSphere Enterprise Plus these toolkits have write-access enabled and provide a scriptable method for managing ESXi hosts." [6]