Security‎ > ‎

Emergency Datacenter Shutdown

posted Oct 25, 2013, 1:17 PM by Kris Knight   [ updated Jun 14, 2016, 11:44 AM ]
Will most likely never be needed however should you ever have a need to power everything off really fast, this does the trick. It will not power hosts off that are in standby. And depending on your environment this may need some editing.  

DO NOT TEST THIS ON A PRODUCTION ENVIRONMENT.  You have been warned.

Incorrect or unauthorized implementation of this script can and will most likely result in the preparation of your resume. I am not liable. Please Know what you are doing before running any PowerShell/PowerCLI scripts.

#####################################################################
#Emergency Shutdown of vCenter Environment
#
#by Virtu-Al modified by KnightUSN 25OCT2013
#
#DO NOT RUN THIS UNLESS YOU HAVE IN WRITING TO DO SO, and in triplicate.
#
#If your vCenter Server and vCenter SQL DB is Physical this should run without a hitch. However, if it is Virtual/VM some code modification is necessary.
#
#Replace the "# For each of the VMs on the ESX hosts" loop with
#
#Foreach ($VM in ($ESXSRV | Get-VM | ?{$_.Name -ne "<Name of vCenter VM>" -or $_.Name -ne "<Name of vCenter SQL VM>" )){#
#####################################################################

# Get All the ESX Hosts in vCenter
# Or select a specific Cluster $ESXSRV = get-cluster "<cluster name>" | Get-VMHost
$ESXSRV = Get-VMHost

# For each of the VMs on the ESX hosts
Foreach ($VM in ($ESXSRV | Get-VM)){
    # Shutdown the guest cleanly
    IF(($VM | Get-view).Guest.ToolsRunningStatus -eq "guestToolsRunning"){
        $VM | ?{$_.PowerState -eq "PoweredOn"} | Shutdown-VMGuest -Confirm:$false
    }
}

# Set the amount of time to wait before assuming the remaining powered on guests are stuck
$TimeOUT = 200 #Seconds

$TimeINT = (Get-Date).TimeOfDay
do {
    # Wait for the VMs to be Shutdown cleanly
    sleep 1.0
    $numvms = ($ESXSRV | Get-VM | Where { $_.PowerState -eq "poweredOn" }).Count
    $Timer = $TimeOUT - [INT]((Get-Date).TimeOfDay - $TimeINT).TotalSeconds
    Write "Waiting for shutdown of $numvms VMs or $Timer seconds"
    } until ((@($ESXSRV | Get-VM | Where { $_.PowerState -eq "poweredOn" }).Count) -eq 0 -or $Timer -le 0)

#Stuck VM Shutdown
Foreach ($VM in ($ESXSRV | Get-VM | ?{$_.PowerState -eq "PoweredOn"})){
    #Stop the hung VMs
    write-host ""
    write-host "unable to shutdown $VM.Name guest cleanly. Initiating forced Power-Off!" -foregroundcolor red
    write-host ""
    $VM | ?{$_.PowerState -eq "PoweredOn"} | Stop-VM -Confirm:$false
}

# Shutdown the ESX Hosts
$ESXSRV | Foreach {Get-View $_.ID} | Foreach {$_.ShutdownHost_Task($TRUE)}

Write-Host "Shutdown Complete"
Comments