Skip to content
UPSmonitor 247-IT

247-IT Guide

UPS shutdown via PowerShell script: what is missing in a real outage

A script that shuts down the Hyper-V hosts during a power outage is written quickly. Which weak spots only show up in a real outage, what a shutdown script must do at a minimum, and when a script is still enough.

01 Situation The script is written quickly. It is rarely tested.

Twenty lines of PowerShell

Many Hyper-V environments are protected against power outages by a home-grown script. That is not a bad start: query the UPS via NUT or SNMP and shut the hosts down with PowerShell, all in twenty lines. It usually looks something like this:

# Typical shutdown script: query NUT, shut everything down on battery
$ups   = 'nas01'                # NUT server
$hosts = 'hv01', 'hv02'         # Hyper-V hosts

while ($true) {
    $tcp = [Net.Sockets.TcpClient]::new($ups, 3493)
    $io  = $tcp.GetStream()
    $w   = [IO.StreamWriter]::new($io); $r = [IO.StreamReader]::new($io)
    $w.WriteLine('GET VAR ups ups.status'); $w.Flush()
    $status = $r.ReadLine()     # e.g. VAR ups ups.status "OB DISCHRG"
    $tcp.Dispose()

    if ($status -match '\bOB\b') {
        foreach ($h in $hosts) {
            Invoke-Command -ComputerName $h -ScriptBlock {
                Get-VM | Where-Object State -eq 'Running' | Stop-VM
                Stop-Computer -Force
            }
        }
        break
    }
    Start-Sleep -Seconds 30
}

In a test it works. In a real power outage it fails for reasons you cannot see in the script.

02 Weak spots Ten things the script above does not handle.

What goes wrong in a real outage

Typical weak spots of home-grown shutdown scripts
Weak spot Consequence
A single reading triggersA UPS self-test or one second of grid fluctuation shuts everything down.
UPS unreachableThe exception ends the script. From then on nobody is monitoring, and nobody notices.
Status only, no runtimeThe script shuts down immediately, even if the battery would last another hour.
No timeout per VMA VM stuck in Windows updates blocks all following VMs and hosts.
Hosts one after another instead of in parallelThe second host only starts once the first is done. The UPS time budget then runs out.
The monitoring computer shuts itself downIf the script runs on hv01, it ends itself before hv02 gets its turn.
CredentialsThe script runs as a scheduled task under a domain admin, often with the password in plain text.
No alert, no logAfter the outage nobody knows whether or when the script ran.
New VMs and hostsA new host is not added to $hosts and stays unprotected at the next outage.
No test modeTesting means really shutting everything down. So nobody tests.
03 Minimum requirements If you stay with a script, build these in.

What a shutdown script must do at a minimum

  1. Confirm repeatedly — trigger only after several consecutive readings on battery, and check once more just before shutting down whether power is back.
  2. Thresholds — evaluate battery charge and runtime, not just the status.
  3. Handle errors — report an unreachable UPS instead of ending the script. And monitor the script itself: is it still running at all?
  4. Timeout per VM — afterwards switch off hard with Stop-VM -TurnOff so a stuck VM does not hold everything up.
  5. Hosts in parallel, own computer last — the monitoring computer only shuts down once all others have their command.
  6. Protect credentials — a dedicated account with the required rights, the password encrypted with DPAPI or a group managed service account.
  7. Log and alert — write every step to the event log and notify on power loss, shutdown and power return.
  8. Test mode — a dry run that only logs what would happen.

Twenty lines quickly become several hundred. They need maintenance whenever hosts, passwords or the UPS change, and usually only one person knows the script.

04 Being fair For some environments a script is enough.

When a script is enough

  1. A single host — without an order across several hosts the script stays manageable. Often Hyper-V's stop action is enough then, see Shutting down Hyper-V VMs in a power outage.
  2. Test environment or lab — where an unnecessary shutdown bothers nobody.
  3. Someone maintains it — with version control, documentation and a yearly test.
05 Implementation What the UPS Hyper-V Shutdown Monitor already covers.

The points above in the UPS Hyper-V Shutdown Monitor

Minimum requirements and how they are covered
Requirement Implementation
Repeated confirmationTriggers only after several readings on battery (default: 3 × 30 s), then a 15 s cancel window if power returns
ThresholdsBattery charge in percent and runtime in seconds, set separately
Handle errorsAlert when the UPS becomes unreachable and when it is reachable again
Timeout per VMShut down or save, switch off hard when the timeout expires (default 120 s, set per host)
Hosts and orderOrder per host: hosts with the same value in parallel, groups one after another, own computer last
Power returnsIf mains power returns after a triggered shutdown, the monitor re-arms for the next outage (Windows event 2002)
Live migration and additional serversLive migration to a partner host still on mains instead of a shutdown; additional servers with their own, earlier runtime threshold — from Pro
CredentialsPasswords encrypted with DPAPI, control via WinRM without an agent
Log and alertLog, shutdown history, email and SNMP trap; Teams, SMS and webhook from Pro
Test modeDry run without commands to the hosts, logging order and timing

The software runs as a Windows service without a signed-in user. New VMs on a configured host are shut down automatically as well.

06 Checklist For scripts and tools alike.

Shutdown checklist

  1. Does not trigger on a single reading
  2. Reports when the UPS is unreachable
  3. Stuck VMs do not hold up the shutdown
  4. All hosts fit into the UPS time budget
  5. Notifies on power loss, shutdown and power return
  6. Was tested in the last year, dry and for real
07 Questions Short answers to common questions.

Frequently asked questions

Can I shut down Hyper-V hosts during a power outage with a PowerShell script?

Yes. The script queries the UPS via NUT or SNMP and shuts down VMs and hosts with Invoke-Command. To work reliably in a real outage, though, it needs repeated confirmation, error handling, timeouts per VM, logging and alerting.

Why is querying the “on battery” status not enough?

Because every self-test and every brief grid fluctuation then triggers a shutdown, and because the script shuts down immediately even if the battery would last a long time. Several consecutive readings and thresholds for battery charge and runtime make sense.

How do I stop a stuck VM from holding up the shutdown?

With a timeout per VM. If the VM is still running afterwards, it is switched off hard with Stop-VM -TurnOff.

Where should the shutdown script run?

On a computer on the same UPS that shuts down last. If it runs on one of the hosts, that host must be at the end of the order.

Instead of a script: ready, tested, reliable

30 days free, every feature included. Repeated confirmation, timeouts, order, alerts and test mode, without a single line of PowerShell.