So after a major power failure where I work occured where the UPS's batteries only ran about 10 minutes and the backup generator didn't kick in, I've been put in charge of writing a script that kicks off to shut down VMs and servers within a given cluster. Now as I'm fairly new to the enviroment here so I'm not sure if all vms have the tools installed. I want to cover all the bases and cover vms that don't have tools installed. What my script currently does is it initiates the guest shutdown on all vms and checks every 10 seconds up to 120 seconds for the VMs to go offline If after 120 seconds there are still vms online it issues a power off command on all servers that haven't shut down. Now this will catch all the VMs but I don't want the machine have to wait the full 2 minutes if it can be avoided (remember this script will be ran when the datacenter goes to UPS power so every watt counts to keep the critical systems online). the script does throw an error when it can't shutdown because no tools are installed so I was thinking I could use a try/catch block to catch the error and send just a strait power off command to those vms. I've attempted to do so, but no success.
Is there a way that I can either catch the error, or shutdown all VMs that don't have tools installed?
Attached is my code maybe you can spot what I can do to shutdown the VMs without tools within the do/while loop when the errors first occur.
Add-PSSnapin VMware.VimAutomation.Core
$server = $args[0]
$cluster = $args[1]
Connect-VIServer -Server $server
$counter = 0
do {
if (Get-Cluster -Name $cluster | get-vm | where {$_.powerstate -eq "poweredon"}){
if ($counter -eq 0) {
Get-Cluster -Name $cluster |get-vm | where {$_.powerstate -eq "poweredon"} | shutdown-VMGuest -Confirm:$false
}
Write-Host "VMs are powered on waiting "(120-$counter)" Seconds"
$counter = $counter + 10
Sleep 10
}
}
while ($counter -le 110) -or ((Get-VMHost | Get-VM | where {$_.powerstate -eq "poweredon"}).count) -ne 0
if ($counter = 120) {
Write-Host "Some VMs failed to shut down gracefully, powering down now"
Get-Cluster -name $cluster |get-vm | where {$_.powerstate -eq "poweredon"} | Stop-VM -Confirm:$false
}
Write-Host "Putting servers into maintenance mode."
Get-cluster -name $cluster | get-vmhost | where {$_.state -eq "connected"} | Set-VMHost -State "Maintenance"
sleep 10
Write-Host "Shutting down servers."
Get-cluster -name $cluster | get-vmhost | where {$_.state -eq "Maintenance"} | Stop-VMHost -Confirm:$false
Disconnect-VIServer -Confirm:$false