HOWTO: Power On a VMware Virtual Machine with PowerCLI (PowerCLI 101)



VMware PowerCLI

Published on 25 April 2016 by Christopher Lewis. Words: 366. Reading Time: 2 mins.

Being able to Power on a Virtual Machine is a PowerCLI 101 subject (right after the Connect-VIServer).

Start-VM -VM "VM Name" -Server "vCenter/ESX Server Name"

However, how about being able to choose what to do with a Virtual Machine based on its current Power Status? That is where (amongst other ways) the PowerShell Switch command comes in.

Firstly we get the Virtual Machine Object using Get-VM into an object called (funnily enough) $VM.

$VM = Get-VM -Name "<Name>" -Location "<vCenter/Host Name>"

Then we use the PowerState property of the Virtual Machine Object to query the power state of that VM and act accordingly.

  • PoweredOn
  • PoweredOff
  • Suspended

There are three defined states according the Virtual Machine Object that we can use in the Switch.

Switch (item)
{
Value A {Expression}
Value B {Expression}
Value X {Expression}
Default {Expression}
}

Whoa there… What is the Default condition for? Well the clue is in the name, the Default condition is only run if no other condition is matched.

For Virtual Machine(s) that are in a PowerState of “Powered On” or “Suspended” we’ll just display a message to that effect. Albeit, you could easily Start the Suspended Machine or Power Off the already Powered On Virtual Machine but that’s not what this post is about! For the Virtual Machine(s) that are Powered Off, we’ll Power them On!

Switch ($VM.PowerState)
{
PoweredOn { Write-Host "$VM already Powered On.";break}
PoweredOff { Write-Host "Powering on $VMName on esx-host-Name"; Start-VM -VM $VM -Server "esx-host-Name";break}
Suspended { Write-Host "$VM suspended.";break}
Default {break}
}

Now (again) we can put all of this logic into a Function called PowerOnVM

Function PowerOnVM ([string] $Name, [string] $Hostname)
{
	$VM = Get-VM -Name $Name -Location $Hostname
	Switch ($VM.PowerState)
	{
		PoweredOn { Write-Host "$VM already Powered On.";break}
		PoweredOff { Write-Host "Powering on $VMName on $Hostname"; Start-VM -VM $VM -Server $Hostname;break}
		Suspended { Write-Host "$VM suspended.";break}
		Default {break}
	}
}

Which can then be called by a script using:

PowerOnVM "vm name" "host/vcenter name"

I’m sure there are PowerCLI wizards out there who can be more efficient in their code and this PowerOnVM function could easily be changed to a ChangeVMPowerState function by Powering Off VMs that were on and vice versa.

Published on 25 April 2016 by Christopher Lewis. Words: 366. Reading Time: 2 mins.