A cheat sheet with common sysadmin tasks for working with VMware, mainly via PowerCLI.

Import VMware CLI module

Add-PSSnapin vmware.vimautomation.core 

Connect NIC at power on

get-vm -name templatetest | Get-NetworkAdapter | Set-NetworkAdapter -StartConnected:$true 

Power on VM

get-vm -name templatetest | Start-VM 

Power off VM

GET-VM VMname | Stop-VM -force 

Show VM IP addresses

Only works with static IPs – may need to adjust the [0]

get-vm | ?{$_.name -match "TUSOE"} | select name, notes, @{N="IP Address";E={@($_.guest.IPAddress[0])}} 

List all VMs in a folder

get-folder Corporate | get-vm | select name 

Basic audit of VM hosts (can copy and paste into excel)

get-vmhost | select name, manufacturer,model,NumCPU,processortype,MemoryTotalGB,parent | Out-GridView 

Get all hostname and models of hosts under EMV folder

get-vmhost -location EMV | select name, model 

VMware PowerCLI

Connect-VIserver localhost Get-VM 

Get MTU settings across all VM Hosts

Get-VMHostNetworkAdapter | select VMhost, Name, IP, PortGroupName,mtu | export-CSV H:\VM-MTU.csv 

Enable SNMP on ESX hosts

#VMWare CLI required
C:\Program Files (x86)\VMware\VMware vSphere CLI\bin>

vicfg-snmp.pl --server SERVER01 --username root --password Pa55word -c public
vicfg-snmp.pl --server SERVER01 --username root --password Pa55word -t MonitoringServerIP@161/public
vicfg-snmp.pl --server SERVER01 --username root --password Pa55word --enable
vicfg-snmp.pl --server SERVER01 --username root --password Pa55word –test 

Check service status and start SNMP

Get-VMHostService | where {$_.key -eq "snmpd"}
Get-VMHostService | where {$_.key -eq "snmpd"} | Start-VMHostService 

Show all snapshots (Excluding VMs named BCP_* )

get-vm | ? {$_.name -notmatch "BCP_*"} | get-snapshot | select vm,name,created,sizeGB | Sort-Object sizeGB | Out-GridView 

Remove and delete VM from disk

Remove-VM -vm VMNAME -DeleteFromDisk -Confirm:$False

Show VM host firewall exceptions


Access VMware direct ESX console

ALT-F1 = Switches to the console 
ALT-F2 = Switches to the DCUI 
ALT-F11 = Returns to the banner screen 
ALT-F12 = Displays the VMkernel log on the console

ALT-F1 = Switches to the console of the service console 
ALT-F2 = Switches to the console of the service console 
ALT-F11 = Returns to the banner screen 
ALT-F12 = Displays the VMkernel log on the console 

Create portgroups on ESX host

# Add DMZ as VLAN 130
$esxcli = Get-EsxCli -VMHost ESX05.domain.com
$esxcli.network.vswitch.standard.portgroup.add("DMZ", "vSwitch3")
$esxcli.network.vswitch.standard.portgroup.set("DMZ", "130") 

Get guest operating system for all VMs

#excludes VMs named BCP_*
get-vm |? {$_.name -notmatch "BCP_*"} | Get-VMGuest | select VM, OSFullName | out-gridview 

Show VMs with Veeam backup attribute

get-vm | get-annotation |?{$_.Value -like '*backup*'} | select AnnotatedEntity, Value | ft -autosize 

VMware tools status check

Get-VM | ? {$_.name -notmatch "BCP_*" -and $_.name -notmatch "EQUINIX*"} | Select PowerState, Name,
@{N=”Tools status”;E={$_.Guest.State}},
@{N=”Tools version”;E={$_.Extensiondata.Config.Tools.ToolsVersion}} | Out-GridView 

Rename a VM

1. Rename the guest O/S
2. Rename the VM in vSphere
3. Perform Storage vMotion (this will rename all the folders/files on the datastore to the new VM name)
4. vMotion back to original storage (if required)

Find/Match up guest Windows disks/vmware disk numbers

Never extend the wrong disk again!
Note: In Windows 2003, you may need to find do this the old fashioned way, by finding the Bus Number/Target ID/LUN which will match up to the VMware virtual Device Node. EG in Windows: Bus Number 0, Target ID 4, LUN 0 equals SCSI(0:4) in VMware

#info on how to match up disks in guest (Windows) and host (vmware)

# RDP to the Windows server (guest OS) and run this
Get-WmiObject Win32_DiskDrive | % {
  $disk = $_
  $partitions = "ASSOCIATORS OF " +
                "{Win32_DiskDrive.DeviceID='$($disk.DeviceID)'} " +
                "WHERE AssocClass = Win32_DiskDriveToDiskPartition"
  Get-WmiObject -Query $partitions | % {
    $partition = $_
    $drives = "ASSOCIATORS OF " +
              "{Win32_DiskPartition.DeviceID='$($partition.DeviceID)'} " +
              "WHERE AssocClass = Win32_LogicalDiskToPartition"
    Get-WmiObject -Query $drives | % {
      New-Object -Type PSCustomObject -Property @{
       DriveLetter = $_.DeviceID
       VolumeName  = $_.VolumeName
        Disk        = $disk.DeviceID
        "UUID/Serial"     = $disk.SerialNumber
        #DiskSize    = $disk.Size
       # DiskModel   = $disk.Model
        Partition   = $partition.Name
       # RawSize     = $partition.Size     
       # Size        = $_.Size
       # FreeSpace   = $_.FreeSpace

# Note drive letter and its corresponding UUID/Serial number

# Eg. 6000c291a30adaabcd06cb3e6db2552c

#### VMware PowerCLI ####
# IF UUID doesn't show up, you may need to update PowerCLI
# list the UUIDs of all HDDs for the server
Get-VM FileServer01 | Get-HardDisk | Select name,filename,capacitygb,@{name="UUID";expr={$_.extensiondata.backing.uuid}} | Sort-Object name
# Find the matching UUID, and note the "Name", eg. "Hard disk 3"
# Fire up vSphere and extend "Hard Disk 3" for your server

#### Windows box #### 
# Return to RDP session, open diskmgmt.msc and hit refresh
# The correct drive should now have extra unallocated space
# Pump up (Extend) the volume

Try this method if the above doesn’t work (eg Win2k3)

# Failsafe method
# Run this on Windows and note the SCSITargetID for the drive(s) in question:

Get-WmiObject Win32_DiskDrive | % {
  $disk = $_
  $partitions = "ASSOCIATORS OF " +
                "{Win32_DiskDrive.DeviceID='$($disk.DeviceID)'} " +
                "WHERE AssocClass = Win32_DiskDriveToDiskPartition"
  Get-WmiObject -Query $partitions | % {
    $partition = $_
    $drives = "ASSOCIATORS OF " +
              "{Win32_DiskPartition.DeviceID='$($partition.DeviceID)'} " +
              "WHERE AssocClass = Win32_LogicalDiskToPartition"
    Get-WmiObject -Query $drives | % {
      New-Object -Type PSCustomObject -Property @{
       DriveLetter = $_.DeviceID
       VolumeName  = $_.VolumeName
        Disk        = $disk.DeviceID
        "UUID/Serial"     = $disk.SerialNumber
       # DiskSize    = $disk.Size
       # DiskModel   = $disk.Model
       # Partition   = $partition.Name
       # SCSIBus = $disk.SCSIBus
       # SCSIPort = $disk.SCSIPort
        SCSITargetId = $disk.SCSITargetId
       # SCSILogicalUnit = $disk.SCSILogicalUnit
       # RawSize     = $partition.Size     
       # Size        = $_.Size
       # FreeSpace   = $_.FreeSpace

# Run this in PowerCLI and note the DiskName(s) for the SCSI_ID(s) that match SCSITargetID from the Windows output
# This needs to be rerun every time a disk is removed or added, as the DiskName can change
$VM = "FileServer01"
$DiskInfo= @()
foreach ($VMview in Get-VM $VM | Get-View){
foreach ($VirtualSCSIController in ($VMView.Config.Hardware.Device | where {$_.DeviceInfo.Label -match "SCSI Controller"})) {
foreach ($VirtualDiskDevice in ($VMView.Config.Hardware.Device | where {$_.ControllerKey -eq $VirtualSCSIController.Key})) {
$VirtualDisk = "" | Select VMname, SCSI_ID, DiskName, DiskSize
$VirtualDisk.VMname = $VMview.Name
$VirtualDisk.DiskName = $VirtualDiskDevice.DeviceInfo.Label
$VirtualDisk.SCSI_ID = "$($VirtualSCSIController.BusNumber) : $($VirtualDiskDevice.UnitNumber)"
$VirtualDisk.DiskSize = $VirtualDiskDevice.CapacityInKB * 1KB / 1GB
$DiskInfo += $VirtualDisk
$DiskInfo | sort SCSI_ID  | ft

Create VM snapshot

get-vm "FileServer01" | new-snapshot -Name "Pre-upgrade" -Description "DR Plan" -Quiesce -Memory

Find PowerCLI version


Display connected VIServers in title bar

This will list the connected vCenter servers in the PowerCLI title bar

$host.ui.RawUI.WindowTitle = "Connected To: $global:defaultVIServers"

Find a VM via its IP address

List all VMs that match an IP or part of an IP address

$list = Get-View -ViewType VirtualMachine | Select name,@{N='IP';E={[string]::Join(',',$_.Guest.ipaddress)}}
$list | ?{ $_.ip -match "" }

Show all VM hosts’ uptime in days

Get-View  -ViewType hostsystem -Property name,runtime.boottime | Select-Object Name, @{N="UptimeDays"; E={((((get-date) - ($_.runtime).BootTime).TotalDays).Tostring()).Substring(0,5)}} | sort name

Show VMs on a certain port group/vmkernel network

Get-VirtualPortGroup -Name ProdNetwork | Get-VM 

Get uptime/boot time of a VM

Get-VM FileServer03 |  Get-Stat -Stat sys.uptime.latest -MaxSamples 1 -Realtime | select Entity,@{Name="Boottime";Expression={(Get-Date).AddSeconds(- $_.value).ToString("dddd/MM/yyyy HH:mm:ss")}},@{Name="UpTime(Seconds)";Expression={($_.value)}}

Show powered on VMs that have NIC disconnected at power on

If any of these VMs are rebooted, they won’t reconnect to the network at power on!
This shows VMs that are running and with NICs that are connected but will become disconnected at next boot

get-vm | ? {$_.PowerState -eq "PoweredOn" } | get-NetworkAdapter | ? {($_.connectionstate -match "NoStartConnected") -and ($_.connectionstate -notmatch "NotConnected")} | select parent, name, networkname, connectionstate 

Storage vmotion VM and convert to thin provisioning

Don’t forget to unmount any connected CD/DVD/ISOs first

Get-VM Server01 | Move-VM -DiskStorageFormat Thin -Datastore "Datastore1" –RunAsync -verbose

Unmount CD/DVD drive/ISO and set to disconnect at startup

Get-VM Server02 | Get-CDDrive |Set-CDDRIVE -StartConnected $False -Connected $False -Confirm:$false

Show running/active tasks (only for current user)

get-task | ? {$_.state -eq "running" } | sort percentcomplete

Copy a file to a VM (max 300MB? need to provide creds of the guest VM)

$creds = get-credential
Copy-VMGuestFile -vm webserver01 -Source C:\bieber-liveset.mp3 -Destination d:\tmp\ -LocalToGuest -GuestCredential $creds

Storage vMotion to a particular datastore (instead of datastore cluster)

Don’t forget to unmount any connected CD/DVD/ISOs first

# Define the datastore
$ds = get-datastore Datastore1
Get-VM "Server01" | Move-VM -Datastore $ds  -verbose –RunAsync

Show vCenter that a VM sits on

Hacky. Handy if you have multiple VIServers connected in PowerCLI and you want to know which VCenter the VM belongs to

get-vm FileServer03 | get-vmhost | Get-Cluster | select uid

Find a VM via its MAC address

get-vm | get-networkAdapter | where {$_.macaddress -eq “00:50:56:A1:EB:18” } | select parent

Find which VM is using a specific ISO file (eg .iso name contains “redhat”)

Get-VM | Get-CDDrive | ? {$_.isopath -match "redhat" }|select parent, isopath

List all VMs with ISOs mapped/connected
Get-VM | Get-CDDrive | ? {$_.isopath -ne $null } | select parent, isopath

Search for an ISO across all datastores

dir -Recurse -Path vmstores:\ -Include *.iso | select name, Datastorefullpath | out-gridview