October 27, 2016

vSphere PowerCLI snippets

A collection of random vSphere PowerCLI snippets that I've either created or gathered from around the internet.  If I haven't lost the source, I'll include a link.

Setup and Connectivity
In version 6.x PowerCLI needs to first to be downloaded from vmware and then installed on your computer.  I heard rumors at vmworld 2016 that this is hopefully changing in some future release.
  • Add PowerCLI snapin, unless it's already loaded. This is required unless you started the PowerCLI on the start menu:
If (!(Get-PSSnapin -name VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) {    Add-PSSnapin VMware.VimAutomation.Core}
  • Connect to a vcenter or server.  -ErrorAction is helpful when scripting.  No use continuing if connection fails:
Connect-VIServer -Server $ServerName -ErrorAction Stop
  • Check for existing connections, then disconnect from all:
If ($global:DefaultVIServers.Count -gt 0){Disconnect-VIServer * -Confirm:$false}

Datastore Stuff
  • List Datastores and count of guests:
Get-Datastore | Select Name, @{N="Count";E={@($_ | Get-VM).Count}}
If I'm searching for multiple unused volumes, I'll save this snippet as Get-DatastoreVMCount.ps1, then run it something like "Get-DatastoreVMCount.ps1 | Where {$_.Count -eq 0} | sort Name".