Flip The Switch

I made a new PowerShell script at work recently. It’s not as big as it looks – all it does is shut down a VMware guest. This assumes you have the PowerCLI modules loaded and are already connected to a VIserver.

Since the “Shutdown-VM” command just initiates a shutdown of a VM guest, I wanted to script something out that would actually pause until the VM is completely shut down.

Function Off-VM

Initiates a VMware VM Guest shutdown and verifies the system is powered off

Uses the Shutdown-VM cmdlet to initiate a guest shutdown, then refreshes the status with
the Get-VM cmdlet

Author: Ben “The Slowest Zombie” Peterson
Version: 1.0
Requirements: PowerShell 3.0

Identifies one or more virtual machines to power off.

The number of times to refresh the virtual machine state before giving up

The number of seconds to wait between each refresh of the virtual machine state

.\Off-VM Virtual05
Shuts down a virtual machine named Virtual05.

Get-VM Virtual* | Off-VM
Shuts down all virtual machines whose names begin with Virtual.
This seems to be non-functional

Off-VM Virtual02,Virtual03 -WaitCycles 1 -WaitTimer 30
Shuts down two virtual machines. Only one status refresh is attempted after 30 seconds.

Author Homepage: http://slowestzombie.net/it_lives

$WaitCycles = 5,
$WaitTimer = 1

foreach ($VM in $Name) {
Write-Verbose $VM”: Selected”
$VMProper = Get-VM $VM
switch (($VMProper).PowerState)
“PoweredOn” {
Write-Verbose $VM”: Powered On”
$VMProper | Shutdown-VMGuest -Confirm:$false | Out-Null
#Write-Host $VM”: Waiting for shutdown to complete” -NoNewline
$i = $WaitCycles
do {
Write-Progress -Activity $VM”: Waiting for shutdown to complete” -Status “Refreshing status $i more times” -PercentComplete ( (($WaitCycles – $i) / $WaitCycles) * 100 )
Start-Sleep -Seconds $WaitTimer
$status = Get-VM $VM
} #do
until ($status.PowerState -eq “PoweredOff” -or $i -eq 0)
if ($status.PowerState -ne “PoweredOff”) {
Write-Error $VM”: Did not power off in the expected time” -ErrorAction Continue
} else {
Write-Verbose $VM”: Powered Off”
} #if
} #PoweredOn
“PoweredOff” {
Write-Verbose $VM”: Powered Off”
} #PoweredOff
default {
Write-Warning $VM”: Not found or in unexpected state”
} #default
} #switch
} # Foreach

} #function Off-VM

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>