PowerCLI Script to Automatically Shut Down VMs in Case of Outage

Introduction

In disaster recovery planning, power loss, HVAC failure, or critical hardware degradation may require a controlled shutdown of virtual infrastructure. Manually powering down hundreds of VMs is slow and error-prone. With PowerCLI, you can automate this process and ensure consistent execution during stressful events.

This article shows you how to:

  • Create a controlled VM shutdown script
  • Filter workloads by priority, tag, or folder
  • Log all actions to disk
  • Integrate into DR runbooks or UPS-triggered events

Step 1: Connect to vCenter

Connect-VIServer -Server "vcenter.lab.local"

You may want to store credentials securely using a credential manager or vault.


Step 2: Define VM Shutdown Order

Option A: By tag (e.g., “Tier1”, “Tier2”)

$tier1 = Get-Tag -Name "Tier1" | Get-TagAssignment | Select -ExpandProperty Entity
$tier2 = Get-Tag -Name "Tier2" | Get-TagAssignment | Select -ExpandProperty Entity

Option B: By folder

$tier1 = Get-Folder -Name "CriticalVMs" | Get-VM
$tier2 = Get-Folder -Name "StandardVMs" | Get-VM

Step 3: Gracefully Shut Down VMs in Order

# Tier 1 VMs
$tier1 | Sort-Object Name | ForEach-Object {
Stop-VMGuest -VM $_ -Confirm:$false
Start-Sleep -Seconds 5
}

# Tier 2 VMs
$tier2 | Sort-Object Name | ForEach-Object {
Stop-VMGuest -VM $_ -Confirm:$false
Start-Sleep -Seconds 5
}

Fallback to Stop-VM if VMware Tools is not installed:

if ($_.ExtensionData.Guest.ToolsStatus -ne "toolsOk") {
Stop-VM -VM $_ -Confirm:$false
}

Step 4: Log Shutdown Activity

$logPath = "C:\Logs\DR_Shutdown_$(Get-Date -Format yyyyMMdd_HHmm).log"

$tier1 + $tier2 | ForEach-Object {
"$($_.Name) shutdown initiated at $(Get-Date)" | Out-File $logPath -Append
}

Step 5: Integrate with Trigger or Task Scheduler

You can call this script with a UPS shutdown trigger or run it every X minutes when DR mode is activated.

powershell.exe -File "C:\Scripts\Shutdown-VMs-DR.ps1"

Diagram: DR Shutdown Flow


Use Case: Emergency Power Event

During a generator or UPS failover, a script like this ensures:

  • Tiered shutdown to avoid VM corruption
  • Compliance with DR runbooks
  • Quick logging for postmortem or audit

Bonus: Include Email Notification (Optional)

Send-MailMessage -To "admin@company.com" -From "vSphereDR@lab.local" `
-Subject "VM Shutdown Triggered" -Body "Shutdown completed at $(Get-Date)" `
-SmtpServer "smtp.lab.local"

Troubleshooting

ProblemSolution
VM does not shut down gracefullyUse fallback Stop-VM method or verify VMware Tools is installed
Tags not resolvingEnsure tags are synced and assigned in vCenter
Log file not createdValidate write permissions for destination folder
Email not sentCheck SMTP relay and authentication settings

Leave a Reply

Discover more from Digital Thought Disruption

Subscribe now to keep reading and get access to the full archive.

Continue reading