Skip to content

Instantly share code, notes, and snippets.

@chris1984
Forked from githubfoam/powerCLI cheat sheet
Last active May 8, 2023 19:08
Show Gist options
  • Save chris1984/d529ca982088001e98f4798e02e35bac to your computer and use it in GitHub Desktop.
Save chris1984/d529ca982088001e98f4798e02e35bac to your computer and use it in GitHub Desktop.
powerCLI cheat sheet
------------------------------------------------------------------------------------------------------------------------------------
Get-Help Get-Snapshot
Get-Help XXX (cmdlet)
REMARKS
To see the examples, type: "get-help Get-Snapshot -examples".
For more information, type: "get-help Get-Snapshot -detailed".
For technical information, type: "get-help Get-Snapshot -full".
For online help, type: "get-help Get-Snapshot -online"
------------------------------------------------------------------------------------------------------------------------------------
#install PowerCLI offline
# download the PowerCLI ZIP file , VMware-PowerCLI-12.7.0-20091289
https://code.vmware.com/web/tool/vmware-powercli
> $PSVersionTable.PSVersion
Major Minor Patch PreReleaseLabel BuildLabel
----- ----- ----- --------------- ----------
7 2 6
> $env:PSModulePath #Check the PowerShell Module path
c:\program files\powershell\7\Modules
#Extract the contents of the ZIP file to the listed folder
c:\program files\powershell\7\Modules
#Unblock the files
> Get-ChildItem * -Recurse | Unblock-File
#verify that the PowerCLI module is available
> Get-Module -Name VMware.PowerCLI* -ListAvailable
------------------------------------------------------------------------------------------------------------------------------------
#install PowerCLI
> Install-Module -Name VMware.PowerCLI -Scope CurrentUser
> Install-Module -Name VMware.PowerCLI -Scope CurrentUser -AllowClobber
PowerCLI allows administrators to manage their VMware environment using the command line. You can simply install VMware PowerCLI straight from the official PowerShell Gallery by issuing the following command from a PowerShell console:
Install-Module VMware.PowerCLI
To allow the execution of local PowerShell scripts, you need to relax the execution policy:
Set-ExecutionPolicy RemoteSigned.
#powershell,verify Installation of PowerCLI
Get-Module -ListAvailable VMware*
#Update PowerCLI
> Update-Module -Name VMware.PowerCLI
------------------------------------------------------------------------------------------------------------------------------------
#Uninstall PowerCLI
#uninstall all official PowerCLI modules except VMware.PowerCLI
(Get-Module VMware.PowerCLI -ListAvailable).RequiredModules | Uninstall-Module -Force
#uninstall the PowerCLI main module
Get-Module VMware.PowerCLI -ListAvailable | Uninstall-Module -Force
------------------------------------------------------------------------------------------------------------------------------------
#PowerShell
Get-ExecutionPolicy
Get-ExecutionPolicy -List
Get-ExecutionPolicy -Scope CurrentUser
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser
Set-ExecutionPolicy RemoteSigned #alternatively
------------------------------------------------------------------------------------------------------------------------------------
#login
>Get-PowerCLIConfiguration
#connect to vCenter with Invalid certificate (self-signed certificate or invalid cert) but shows with certificate warning.
>Set-PowerCLIConfiguration -Scope User -InvalidCertificateAction warn
# Connects to a vSphere server by using the User and Password parameters
>Connect-VIServer -Server 10.23.112.235 -Protocol https -User admin -Password pass #login via CLI
>Connect-VIServer -Server 10.35.1.200 -credential $(Get-Credential) #login via windows pop-up menu
>Connect-VIServer -Menu #login via windows pop-up menu without server parameters
>Disconnect-VIServer #end session
--------------------------------------------------------------------------------------------------------------------------------------------
Get-VM | Get-Snapshot|Select VM,Name
get-vm -name VMNAME | get-snapshot
Get-Snapshot -VM VMNAME -Name 'Before ServicePack 2' #Retrieves the snapshot named "Before ServicePack2" of the VM virtual machine.
create a new snapshot
New-Snapshot -VM Test-1 -Name 'This is a test snapshot' -Description 'Testing this out' -Quiesce -Memory
New-Snapshot -VM VM -Name BeforePatch
New-Snapshot -VM VM2 -Name PoweredOnVM -Memory $true
revert a VM to a snapshot
Set-VM -VM Test-1 -Snapshot (Get-Snapshot -VM Test-1 -Name 'This is a test snapshot'
Remove a snapshot
> Get-Snapshot -VM Test-1 | Remove-Snapshot -RemoveChildren
filter your request by using the Where-Object cmdlet and use the Guest property,
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-View -Viewtype VirtualMachine -Property name, guest.ipaddress
Get-VMHost #ESXi Hosts
Get-VMHost | format-list -Property Name,Version
Get-VMHost | fl #Detailed Information on ESXi Hosts
Get-VMHost -Name esxiserver | Get-VM
Start-VM "Tiny Linux template" #Power On a VM
Stop-VM "Tiny Linux template" #Power Off a VM
Restart-VM "Tiny Linux template"
Shutdown-VMGuest ‑VM <vm>
Restart-VMGuest ‑VM <vm>
#(dis)Mounts the VMware Tools CD installer
Mount-Tools ‑VM <vm>
Dismount-Tools ‑VM <vm>
# 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 esxiserver | 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 esxiserver | 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
Get-Log -Bundle -DestinationPath C:\vSphere_logs #Generate Diagnostic Log Bundle on ESXi Host or vCenter
# This command will give you a list of all your DRS Affinity rules:
Get-DrsRule | Select Name, Enabled, Type, @{Name="VM"; Expression={ $iTemp = @(); $_.VMIds | % { $iTemp += (Get-VM -Id $_).Name }; [string]::Join(";", $iTemp) }} | export-csv c:\temp\DRSRules.csv
# This will give you IP address, name, notes, folder and guest ID:
Get-vm | where { $_.PowerState -eq “PoweredOn”} | Select Name,Notes,Folder,GuestID,@{N="IP Address";E={@($_.guest.IPAddress[0])}} | export-csv c:\temp\VMsOn.csv
# This will give you a list of all VMs that are powered on:
Get-vm | where { $_.PowerState -eq “PoweredOn”} | export-csv c:\temp\VMsOn.csv
This script will give you a list of all Datastores and a breakdown of the remaining space:
Get-VM |
Select Name,
@{N="Datastore";E={[string]::Join(',',(Get-Datastore -Id $_.DatastoreIdList | Select -ExpandProperty Name))}},
@{N="UsedSpaceGB";E={[math]::Round($_.UsedSpaceGB,1)}},
@{N="ProvisionedSpaceGB";E={[math]::Round($_.ProvisionedSpaceGB,1)}},
@{N="Folder";E={$_.Folder.Name}} |
Export-Csv C:\temp\VMsDatastores.csv -NoTypeInformation -UseCulture
This command will give you a .csv file containing all snapshots outstanding within your vCenter environment:
get-vm | get-snapshot | export-csv c:\temp\snapshots.csv
This command will show you all the VMs with ISO files mounted:
Get-VM | FT Name, @{Label="ISO file"; Expression = { ($_ | Get-CDDrive).ISOPath }}
This command will give you information about your hosts:
get-vmhost | Select Name,@{N=”Cluster”;E={Get-Cluster -VMHost $_}},@{N=”Datacenter”;E={Get-Datacenter -VMHost $_}} | Export-csv c:\temp\hostinventory.csv
This will give you the free space remaining in all your datastores:
Get-Datastore | Select Name,CapacityGB,FreeSpaceGB,state | sort -Property FreeSpaceGB -Descending | Export-Csv C:\Scripts\vCenter\DatastoreReport.csv -NoTypeInformation -UseCulture
This will give you all the thick provisioned VMs in your environment:
Get-Datastore | Get-VM | Get-HardDisk | Where {$_.storageformat -eq "Thick" } | Select Parent, Name, CapacityGB, storageformat | Export-Csv C:\temp\VMsThick.csv -NoTypeInformation -UseCulture
This will give you all the thin provisioned VMs in your environment:
Get-Datastore | Get-VM | Get-HardDisk | Where {$_.storageformat -eq "Thin" } | Select Parent, Name, CapacityGB, storageformat | Export-Csv C:\temp\VMsThin.csv -NoTypeInformation -UseCulture
This command translates the HostID to the host DNS name:
Get-VMHost | Select ID,name
This command will show you information on your vSwitches and port groups:
Get-VirtualPortGroup | select Name,VirtualSwitch,VLanId,VMHostID | Export-Csv C:\temp\VMHostNetworkInfo.csv
Get VM disk info
Get-VM -Name exchange1 | Get-HardDisk | Format-List
Find Vm’s Created last 10 days
Get-VIEvent -maxsamples 10000 |where {$_.Gettype().Name-eq “VmCreatedEvent” -or $_.Gettype().Name-eq “VmBeingClonedEvent” -or $_.Gettype().Name-eq “VmBeingDeployedEvent”} |Sort CreatedTime -Descending |Select CreatedTime, UserName,FullformattedMessage -First 10
Updating VMware Tools without reboot:
Get-VMGuest -VM $vm | Update-Tools -NoReboot
Searching for entries in events in vCenter:
foreach ($vmm in get-vm * ) { $vmm |Get-VIEvent -Start 2020.03.23 -MaxSamples 1000 | ? FullFormattedMessage -Match Ethernet0 | select {$vmm.Name} , CreatedTime,FullFormattedMessage }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment