Introduction

VMware PowerCLI is a command-line and scripting toolset for managing VMware environments via powershell. It allows administrators and IT professionals to interact with VMware infrastructure, including vSphere, vCenter Server, ESXi hosts, virtual machines, and more, through PowerShell commands and scripts.

Using PowerCLI, you can perform a wide range of tasks, including:

  • Creating and configuring virtual machines.
  • Managing resource pools, clusters, and datastores.
  • Monitoring and reporting on performance metrics.
  • Managing vCenter Server settings and configurations.
  • Automating backup and restore operations.
  • Deploying templates and customizing virtual machine configurations.
  • Managing networking settings, such as virtual switches and network adapters.
  • Scripting complex workflows involving multiple VMware components.
  • PowerCLI is particularly valuable for larger VMware environments, as it streamlines administrative tasks and reduces the potential for human error. By leveraging the scripting capabilities of PowerShell, administrators can create reusable and standardized automation scripts, saving time and effort.

To get started with PowerCLI, you need to have PowerShell installed on your system along with the VMware PowerCLI module. You can then launch PowerShell and import the PowerCLI module to start using its commands and scripting capabilities.

Start using this module

Installing

To start using the powerCLI, you need to install it on a windows VM.

Install-Module -Name VMware.PowerCLI

If you got the following error:

WARNING: Unable to download from URI 'https://go.microsoft.com/fwlink/?LinkID=627338&clcid=0x409' to ''.
Install-PackageProvider : No match was found for the specified search criteria for the provider 'NuGet'. The package provider requires 'PackageManagement' and 'Provider' tags. Please check if the specified package has the tags.

Try to use this command before installing the module:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Check the module version.

Get-Module -ListAvailable VMware* 

Update PowerCLI before using it, to ensure you got the latest module version.

Update-Module -Name VMware.PowerCLI

VMware PowerCLi Cheat sheet

# Module And Configuration
Get-PowerCLIConfiguration # show current config
Set-PowerCLIConfiguration -Scope User -InvalidCertificateAction warn  # To prevent connection failure due to certificate.
Import-Module VMware.PowerCLI # Load module

# Connect to server
Connect-VIServer -Server <host/vcenter> -credential $(Get-Credential) # Connect with credential popup.
Connect-VIServer -Menu # Connect with Menu/wizard. The listed VM will be shown. 
Disconnect-VIServer # disconnect Session.

# Host Management
Add-VMHost <fqdn or ip> ‑Location (Get-Cluster <cLustername>) ‑User root ‑Password <password> # Add a new ESXi to the inventory
Add-VMHost <fqdn or ip> ‑Location (Get-Cluster <cLustername>) ‑User root ‑Password <password> # Set a host to maintenand mode

# Power operations on ESXi
Restart-VMHost ‑VMHost <host> # Restart Host
Stop-VMHost ‑VMHost <host> # Shutdown Host
Get-VMHostService <host> # Retrieves information about host services
Get-VMHostService <host> | ? {($_.Key ‑eq "TSM-ssh")} | Restart-VMHostService # Restart a specific host service

# Cluster Management
Get-Cluster ‑Name <clustername> # Get cluster information
Set-Cluster ‑Cluster <cluster> ‑HAEnabled:$true ‑HAAdmissionControlEnabled:$true # Enable HA on cluster
Set-Cluster ‑Cluster <cluster> ‑DRSEnabled:$true ‑DRSAutomationLevel "FullyAutomated" # Enable DRS on cluster
Set-Cluster ‑Cluster <cluster> ‑EVCMode "intel-nehalem" # Set EVC mode on cluster

# VAPP Management
Export-VApp ‑vApp <vapp> ‑Destination "c:\vapps\" ‑Format Ova # Export a vApp in OVA format
Import-vApp ‑Source "c:\vapps\appliance.ova" ‑Datastore <datastore> ‑VMHost <vmhost> # Import OVA file as vApp
Set-VApp ‑VApp <vapp> ‑MemExpandableReservation:$true ‑MemReservationGB 2 ‑MemLimitGB 4 # Configure memory ressources for a vApp

# VM Power Management
Get-VM <vmname>
Start-VM <vmname> # Power On a VM
Stop-VM <vmname> # Power Off a VM
Restart-VM <vmname> # Restart VM
Shutdown-VMGuest ‑VM <vmname> # Shutdown VM via VMguest
Restart-VMGuest ‑VM <vmname> # Restart VM via VMGuest

Get-VM <vm> | Open-VMConsoleWindow # Open console in the web browser
Set-VM ‑VM <vm> ‑ToTemplate ‑Name <templatename> # Convert a VM to a template
New-CDDrive ‑VM <vm> ‑ISOPath "[<datastorename>] ISO\sample.iso" # Connect ISO file to a VM
Get-CDDrive ‑VM <vm> | Set-CDDrive ‑connected 0 ‑StartConnected 0 ‑NoMedia # Disconnect any CD drive from a VM
New-HardDisk ‑VM <vm> ‑CapacityGB 10 ‑Persistence persistent # Attach a new persistent disk

# Snapshot Management
Get-VM | Get-Snapshot | Select VM,Name # Get all VM snapshot.
Get-VM -Name <vm> | get-snapshot # Get single VM snapshot
Get-Snapshot -VM <vm> -Name 'Before ServicePack 2' # Get VM snapshot with specific Name.

# Create snapshot.
New-Snapshot -VM <vm> -Name 'SnapshotName' -Description 'this is a test snapshot' -Quiesce -Memory # Create a new VM Snapshot
New-Snapshot -VM <vm> -Name BeforePatch # Create a new VM Snapshot without Memory.
New-Snapshot -VM <vm> -Name PoweredOnVM -Memory $true # Create a new VM Snapshot with Memory.

# Revert back VM to a snapshot
Set-VM -VM VMName -Snapshot (Get-Snapshot -VM VMName -Name 'This is a test snapshot')

# Remove a Snapshot
Get-Snapshot -VM Test-1 | Remove-Snapshot -RemoveChildren # Remove snapshot and its all snapshot children.
# Use Where-Object cmdlet to filter by the OS type.
Get-VM | Where-Object {$_.Guest -like "*Centos*"}
Get-VM | Where-Object {$_.Guest -like "*Windows Server 2012*"}
Get-VM | Where-Object {$_.Guest -like "*Windows Server 2016*"}

# Get VM Property
Get-View -Viewtype VirtualMachine -Property name, guest.ipaddress
Get-VMHost # List the ESXi Hosts
Get-VMHost | format-list -Property Name,Version
Get-VMHost | fl # Detailed Information on ESXi Hosts

# Get VM on host
Get-VMHost -Name $ESXiHostServer | Get-VM

# Mount/Dismount the VMware Tools CD installer. 
Mount-Tools ‑VM $VMName
Dismount-Tools ‑VM $VMName

# SSH and Esxi Shell Status TSM – – Denotes Esxi Shell
Get-VMHost| Get-VMHostService | Where-Object {$_.Key -like "TSM*"}
Get-VMHost -Name esxiserver | Get-VMHostService | Where-Object {$_.Key -like "TSM*"}

# Enabling SSH And Shell
Get-VMHost -Name $ESXiHostServer | Get-VMHostService | Where-Object {$_.Key -like "TSM*"}| Set-VMHostService -policy "on"
Get-VMHost | Get-VMHostService | Where-Object {$_.Key -like "TSM*"}| Set-VMHostService -policy "on"
Restart SSH And Shell
Get-VMHost -Name $ESXiHostServer  | Get-VMHostService | Where-Object {$_.Key -like "TSM*"}| Restart-VMHostService
Get-VMHost | Get-VMHostService | Where-Object {$_.Key -like "TSM*"}| Restart-VMHostService

# list machines loaded with ISOs Unnecessarily
Get-VM | Get-CDDrive | where-object{$_.isopath -notlike $null} | FT Parent,Isopath –AutoSize
Get-VM | where-object {$_.PowerState -eq "PoweredOff"} #VMs that are in the PoweredOff state
Get-VM | where-object {$_.PowerState –eq “PoweredOff”} | Start-VM

Get-VM | where-object {$_.NumCpu –gt 1 } # VMs more than 1 CPU assigned
Get-vm | where-object {$_.MemoryGB -eq 4 } | select -ExpandProperty Name | out-file c:\tmp\VMs.txt #VMs w 4GB memory

Get-VirtualSwitch #the virtual switches configured
Get-VirtualSwitch -Name vSwitch8
Get-VirtualSwitch -Name vSwitch8 | fl
Get-VirtualSwitch | fl

Get-VirtualPortGroup #virtual port groups
Get-VM | Where-Object { ($PSItem | Get-NetworkAdapter | where {$_.networkname -match "DPortgroup"})} #VMs inside port group DPortGroup

# Getting OS Version Information on VMs
Get-VM | Sort-Object -Property Name | Get-View -Property @("Name", "Config.GuestFullName", "Guest.GuestFullName") | Select-Object -Property Name, @{N="Configured OS";E={$_.Config.GuestFullName}}, @{N="Running OS";E={$_.Guest.GuestFullName}}
# txt output
Get-VM | Sort-Object -Property Name | Get-View -Property @("Name", "Config.GuestFullName", "Guest.GuestFullName") |Select-Object -Property Name, @{N="Configured OS";E={$_.Config.GuestFullName}}, @{N="Running OS";E={$_.Guest.GuestFullName}}  | out-file c:\tmp\VMswOS.txt
#csv output
Get-VM | Sort-Object -Property Name | Get-View -Property @("Name", "Config.GuestFullName", "Guest.GuestFullName") |Select -Property Name, @{N="Configured OS";E={$_.Config.GuestFullName}}, @{N="Running OS";E={$_.Guest.GuestFullName}} | Export-CSV C:\tmp\report.csv -NoTypeInformation 

Invoke-VMScript -VM WindowsVM -ScriptText "dir C:\" -GuestUser administrator -GuestPassword pass2

Get-View -ViewType VirtualMachine -Filter @{"Name" = "WindowsVM"}
$VM = Get-View -ViewType VirtualMachine -Filter @{"Name" = "WindowsVM"}
$VM.Guest
$VM.Guest.GuestFullName

# Datastore Management
Get-Datastore ‑Name <dsname> # Get datastore information
New-Datastore ‑Nfs ‑VMHost <host> ‑Name <dsname> ‑Path </path/folder> ‑NfsHost <nfsserver> # Create (NFS|VMFS) datastores
New-Datastore ‑Vmfs ‑VMHost <host> ‑Name <dsname> ‑Path <scsiLun.CanonicalName>

# Network Management
Get-VDSwitch ‑name <name> # Get vSphere distributed switch or port group
Get-VDPortgroup ‑Name <name>
New-VDSwitch ‑Name <dvsname> ‑Location <datacenter> # Create a vSphere distributed switch
New-VDPortgroup ‑VDSwitch <dvswitch> ‑Name <pgname> ‑NumPorts 8 ‑VLanId 4 # Create a distributed port group
Export-VDSwitch ‑VDSwitch <dvswitch> ‑Destination "c:\mybkp.zip" ‑WithoutPortGroups # Backup/Export of a vSphere distributed switch

Get-Log -Bundle -DestinationPath C:\vSphere_logs #Generate Diagnostic Log Bundle on ESXi Host or vCenter