Published on

PowerCLI Commands

Authors
  • Name
    Jackson Chen

VMware PowerCLI

VMware PowerCLI is a command-line and scripting tool built on Windows PowerShell, and provides more than 800 cmdlets for managing and automating vSphere, VMware Cloud Director, vRealize Operations Manager, vSAN, NSX-T Data Center, VMware Cloud Services, VMware Cloud on AWS, VMware HCX, VMware Site Recovery Manager, and VMware Horizon environments.

VMware PowerCLI - Automate and Manage

https://developer.vmware.com/powercli

PowerCLI download, documentation and reference

https://code.vmware.com/web/tool/12.3.0/vmware-powercli

PowerCLI Cmdlet References

https://code.vmware.com/docs/5060/cmdlet-reference

Download and Reference

https://code.vmware.com/web/tool/12.3.0/vmware-powercli

https://developer.vmware.com/web/tool/12.4/vmware-powercli

PowerCLI User Guide

https://code.vmware.com/docs/11860/powercli-12-0-0-user-s-guide

VMware PowerCLI 11.5 User Guide

VMware PowerCLI 12.3 User Guide

VMwaer PowerCLI Blog

This is a very blog about VMware PowerCLI

https://blogs.vmware.com/PowerCLI/

VMware vSphere and vSAN Cmdlets

It has very detail vSphere and vSAN Cmdlets

https://developer.vmware.com/docs/powercli/latest/products/vmwarevsphereandvsan/

Basic Commands and Tutorial

Helpful beginner's tutorial

https://adamtheautomator.com/powercli-tutorial/

Set-PowerCLIConfiguration -Scope User -ParticipateInCeip $false
Set-ExecutionPolicy RemmoteSigned

Connect-VIServer <vcenter-fqdn | ip-address > -User <adminuser>   # connect to vCenter
Connect-VIServer <vCenter> -Credential $myCredentialObject

Get-VMHost      # List ESXi hosts
Get-VM          # List all VMs in vCenter
Start-VM  "VM Name"     # Start the VM
Stop-VM  "VM Name"      # Power off VM
Restart-VM  "VM Name"   # Restart VM

Get-VirtualSwitch
Get-VirtualPortGroup

Get-Log -Bundle -Destination c:\vSphere_Logs    # Generate diagnostic log bunndle

PowerCLI Cheatsheet

VMware PowerCLI 6.5 CheatSheet

https://www.turbogeek.co.uk/my-cheat-sheets/

PowerCLI Module for managing vCenter Single Sign-On

https://williamlam.com/2020/10/powercli-module-for-managing-vcenter-single-sign-on-sso.html

PowerCLI team has just released an Open Source Module called VMware.vSphere.SsoAdmin

# Import SSO module
Import-Module ./VMware.vSphere.SsoAdmin.psd1
Connect-SsoAdminServer -Server vcsa.primp-industries.com -User *protected email* -Password <pwd> -SkipCertificateCheck
Get-SsoPasswordPolicy   # retrieve SSO password policy
Get-SsoLockoutPolicy    # retrieve SSO lockout policy

# Create SSO user
New-SsoPersonUser -User lamw -Password 'MyStrongPa$$w0rd' -EmailAddress '*protected email*' -FirstName 'William' -LastName 'Lam'
Get-SsoPersonUser -Name lamw -Domain vsphere.local
Remove-SsoPersonUser -User (Get-SsoPersonUser -Name lamw -Domain vsphere.local)

# Disconnect from SSO endpoint
Disconnect-SsoAdminServer -Server $Global:DefaultSsoAdminServers[0]

Retrieving vSphere Distributed Switch (VDS) DVPort ID & Stats using PowerCLI

https://williamlam.com/2021/07/quick-tip-retrieving-vsphere-distributed-switch-vds-dvport-id-stats-using-powercli.html

Normally getting output from an ESXi host using a classic CLI called esxcfg-vswitch, there are a number of DVPort IDs which are either mapped to a physical NIC on the ESXi host or to a specific VM and its network adapter, if there is more than one.

esxcfg-vswitch -l

Note: Although PowerCLI does provide some higher level cmdlets for managing VDS and Distributed Virtual Portgroups (DVPG), not everything that is available in VDS API is available through these higher level cmdlets, but that does not mean you can not use PowerCLI to easily retrieve all this additional information.

Look at the vSphere API documentation for DVPort to explore what else can be retrieved.

# Retrieve the basic DVPort ID and Client information
$vds = Get-VDSwitch -Name VDS
$ports = $vds.ExtensionData.FetchDVPorts($null)
$results = @()
foreach ($port in $ports | Sort-Object -Property key) {
    $tmp = [pscustomobject] @{
        DVPortID = $port.key;
        Client = $port.state.RuntimeInfo.LinkPeer
    }
    $results += $tmp
}
$results

# For each DVPort, there are also a number of statistics that can be retrieved by looking at the state.stats property.
$vds = Get-VDSwitch -Name VDS
$ports = $vds.ExtensionData.FetchDVPorts($null)
foreach ($port in $ports | Sort-Object -Property key) {
    $tmp = [pscustomobject] @{
        DVPortID = $port.key;
        Client = $port.State.RuntimeInfo.LinkPeer
        BytesInUnicast = $port.state.stats.BytesInUnicast
        BytesOutUnicast = $port.state.stats.PacketsInBroadcast
    }
    $results += $tmp
}
$results

Shutdown entire vSAN cluster

When vSAN connected network maintenance required, or datacenter move required, the entire vSAN cluster will be shutdown to prevent host isolation.

#********** To reduce load PowerCli module time ******************
# Disable Internet Options "Check for publisher's certificate revocation" by uncheck the item
Set-ItemProperty -path “HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings” -Name CertificateRevocation -Value 0

# Disable 'Check for publisher's certificate revocation'
set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\WinTrust\Trust Providers\Software Publishing\" -name State -value 146944
# To Enable it again
set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\WinTrust\Trust Providers\Software Publishing\" -name State -value 146432

#**** Load PowerCLI module
Import-Module VMware.PowerCLI

# Variables
$vCenterVM = Get-VM -Name "vCenter-FQDN | vCenter-Name"

# Connect to vCenter
Connect-VIServer -Server <vCenter-FQDN | 4vCenterVM>

# Verify virtual machines
Get-VMHost "ESXi-host-FQDN|IP-address" | Get-VM | ?{$_.powerstate -eq 'PoweredOn'}
    # Get all VMs from the ESXi host and filter those powered on
Get-cluster "Cluster-Name" | Get-VM | ?{$_.powerstate -eq 'PoweredOn'}  
    # Get all VMs from the VMware cluster
Get-DataCenter "datacenter-name" | Get-VM | ?{$_.powerstate -eq 'PoweredOn'}
    # Get all VMs from the datacenter

# *** Shutdown all VMs and ESXi Hosts, except vCenter VM and ESXi host that hosting vCenter ***
Get-VM -Server $vCentervM | ?{($_.Name -ne $vCenterVM) -and ($_.powerstate -eq 'PoweredOn)} | shutdown-VMGuest -Confirm:$false
While ((Get-VM -Server $vCenterVM | ?{$_.PowerState -ne 'PowerOff'}).Count -ne 0) {
    Sleep 10
}

# If VM refuse to shutdown gracefully
Get-VM | Where-Object {($_.Name -ne $vCenterVM) -and ($_.powerstate -eq 'PoweredOn)} | Stop-VM -Confirm:$false     

# After all VMs, except vCenter VM have been shutdown, put all ESXi hosts to maintenance, except the one hosting vCenter
Get-VMHost -Server $vCenterVM | ?{Get-VM -Location $_).Count -eq 0} | Set-VMhost -State Maintenance -Confirm:$false

#*** If ESXi hosts are vSAN cluster nodes, set No Data Migration
# -VsanDataMigrationMode <Full | EnsureAccessibility | NoDataMigration>
Get-VMHost -Server $vCenterVM | ?{Get-VM -Location $_).Count -eq 0} | Set-VMhost -State Maintenance -VsanDataMigrationMode NoDataMigration -Confirm:$false

# Shutdown ESXi hosts after put them into maintenance mode
Get-VMHost -Server $vCenterVM | ?{Get-VM -Location $_).Count -eq 0} | Stop-VMHost -Confirm:$false
while((Get-VMHost | where{(Get-VM -Location $_).Count -eq 0}).Count -ne 0){
  sleep 10
}

# Disconnect from vCenter
Disconnect-VIServer -Server $vCenterVM -Confirm:$false

#*** Shutdown vCenter and last ESXi host, hosting the vCenter ***
Connect-VIServer -Server $vCenterVM.VMHost.Name -user root -password <esxi-root-password>
Get-VM -Server $vCenterVM.VMHost.Name | Shutdown-VMGuest -Confirm:$false
while((Get-VM -Server $vcVm.VMHost.Name | where{$_.PowerState -ne 'PoweredOff'}).Count -ne 0){
  sleep 10
}

Get-VMHost -Name $vcVm.VMHost.Name | Stop-VMHost -Confirm:$false
Disconnect-VIServer -Server $vcVm.VMHost.Name -Confirm:$false -Force

vMotion VM across vCenter SSO domain with multiple network adapters

https://communities.vmware.com/t5/VMware-PowerCLI-Discussions/move-vm-script-placing-port-groups-on-wrong-adapters-for-VMs/td-p/2301303

https://communities.vmware.com/t5/VMware-PowerCLI-Discussions/Move-VM-VMs-with-Multiple-Network-Interfaces/td-p/2983863

https://thesleepyadmins.com/2021/01/23/vmware-powercli-integrated-authentication-issues/

#***********************
# Cross-SSO-VM-Migration.ps1
#
# vMotion VM with multiple network adapter
# across SSO vCenters
#

# Import VMware PowerCLI module
Import-Module VMwarePowerCLI

# Variables
$srcvCenter = 'source vCenter FQDN / IP'
$scvvCenterUsr = 'administrator@vsphere.local'      # Enter valid vCenter admin login name
$srcvCenterPwd = 'xxxxxxx'      # Or using secure password method
$vmName = 'VM to be migrated'

$dstvCenter = 'dest vCenter FQDN / IP'
$dstvCenterUsr = 'administrator@vsphere.local'      # Enter valid vCenter admin login name
$dstcvCenterPwd = 'xxxxxxx'      # Or using secure password method
$dstESXName = 'ESXi hosts FQDN that VM will be migrated to'
$destvSwitch = 'dest distribute vSwitch name'
$dstDatastoreName = 'dst datastore name'

#
# When cross vCenter SSO with different vds portgroup name
# mapping is required
# e.g. VM has 3 network adapters
# Using an array
$dstVMPortGrps = ('pg1','pg2','pg3')

#
# Create vCenter connections
# 
$srcvCenterCon = Connect-VIServer -server $srcvCenter -user $scvvCenterUsr -password $srcvCenterPwd
$dstvCenterCon = Connect-VIServer -server $dstvCenter -user $dstvCenterUsr -password $dstcvCenterPwd

# 
# Migrate one or more VMs
# 
# $VMs = ('vm1', 'vm2')
# $VMs = <get VMs with conditions or from an input file>
$vm = Get-VM -name $vmName -server $srcvCenterCon

# Obtain source VM network adapters
$vmNetworks = Get-Networkadapter -vm $vm

# Get destion ESXi host object
$dstESXHost = Get-VMHost -name $dstESXName -server $dstvCenterCon

# Create destination port group array
$dstNwPorts = @()
ForEach ($vmportgrp in $dstVMPortGrps) {
    $dstNwPorts += Get-VirtualPortGroup -virtualSwitch $destvSwitch -Name $vmportgrp -VMHost $dstESXHost
}

# Get destination datastore object
$dstDatastore = Get-Datastore -Name $dstDatastoreName -server $dstvCenterCon

#
# Migrate the VM
# Or, migrate mutiple VMs
# 
Move-VM -VM $vm -Destination $dstESXHost -NetworkAdapter $vmNetworks \
    -PortGroup $dstNwPorts -Datastore $dstDatastore