Shutting down a Virtual Machine using PowerCLI

VMware PowerCLI allows us to shutdown a guest operating system on a virtual machine (assuming VMTools are installed) but the command to do this- Shutdown-VMGuest -returns straight away. In a script we may wish to wait for the VM to power down before continuing, this can be done as follows.

The text myvirtualcenterserver and myvirtualmachinename in the script below should be replaced with the appropriate values.

 1#Load the VMWare PowerCLI command set
 2add-pssnapin VMWare.VimAutomation.Core
 3#Connect to the Virtual Center Server
 4Connect-VIServer -Server myvirtualcenterserver
 5#Get the VM
 6$MyVM = Get-VM -Name myvirtualmachinename
 7#Initiate Shutdown of the OS on the VM if it is on.
 8if ($MyVM.PowerState -eq "PoweredOn") {
 9 Write-Host "Shutting Down" $MyVM
10 Shutdown-VMGuest -VM $MyVM
11 #Wait for Shutdown to complete
12 do {
13  #Wait 5 seconds
14  Start-Sleep -s 5
15  #Check the power status
16  $MyVM = Get-VM -Name myvirtualmachinename
17  $status = $MyVM.PowerState
18 }until($status -eq "PoweredOff")
19}