Here is a script that can be used in conjuction with a UPS shutdown utility like APC Powerchute to shutdown all VMs and ESX hosts automatically if a power loss has been detected by the UPS. This script is a configure it once and forget it script. It queries the vCenter server for a list of all VMs and ESX hosts and shuts them all down (VMs first and Hosts later).
Pre-Requisites:
- vCenter Server.
- VMWare Powershell.
- Any UPS Software that can execute a script when a power loss has been detected by the UPS. (Eg- APC Powerchute)
Here’s the script:
Connect-VIServer -Server xxx.xxx.xxx.xxx -Protocol http -User [username] -Password [password]
# List All the ESX Hosts
$ESXSRV = Get-VMHost
# For each of the VMs on the ESX hosts
Foreach ($VM in ($ESXSRV | Get-VM)){
# Shutdown the guest cleanly
$VM | Shutdown-VMGuest -Confirm:$false
}
# Set the amount of time to wait before assuming the remaining powered on guests are stuck
$waittime = 240 #Seconds
Start-Sleep $Waittime
$ESXSRV | Foreach {Get-View $_.ID} | Foreach {$_.ShutdownHost_Task($TRUE)}
Write-Host "Shutdown Complete"
Do the following to run this script via a UPS shutdown utility:
- Save the script to a location of your choice as a PS1 file – Eg: C:\Scripts\PowerOffAll.ps1
- Replace [username] and [password] with the admin username and password for the vCenter server in the Powershell script.
- Change the
$waittimevalue to a high enough value (in seconds) that would allow all your VMs to shutdown. This value would vary from network to network. You might have to try shutting down your VMs to find out the server that shuts down last and use that time in this script.
To execute this powershell script from a UPS software you will need to create this batch file to be able to call this powershell script. Save the following code to a batch file (for example – C:\Scripts\PowerOffAll.bat):
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -PSConsoleFile "C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\vim.psc1" "& "C:\Scripts\PowerOffAll.ps1"
The above script assumes that the vCenter server is running a 64-bit OS (which would be the case if you are using vCenter server version 4.1)
For a x86 server, the code, for example would be:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -PSConsoleFile "C:\Program Files\VMware\Infrastructure\vSphere PowerCLI\vim.psc1" "& "C:\Scripts\PowerOffAll.ps1"
If you face issues with running the script, you might need to check the Powershell execution policy by running: Get-ExecutionPolicy. If it is set to Restricted or AllSigned, you may have issues.
To ensure that you run this script without issues, change the execution policy by running this command: Set-ExecutionPolicy -bypass.
All you need to do now is to configure your UPS software to run this script when the low battery threshold is reached – and – TEST!
Drop me a line if this has helped you!

Recent Comments