#PSTip Offer Delayed Restart with Abort Functionality

Note: This tip requires PowerShell 2.0 or above.

Restart-Computer, no surprise, does the job of restarting a computer but there are times when you want to add the functionality to abort a restart. Something along the lines of “Restarting computer in 30 seconds, Press any key to cancel…”. It reminds me of good, old days of batch scripting.

The function Restart-ComputerWithDelay is a quick and dirty way to achieve this functionality and also provides a countdown timer.

Function Restart-ComputerWithDelay {
        [int]$TimeOutinSeconds = 30,
        [string[]]$ComputerName = $env:COMPUTERNAME

    Write-Host "Press any key to abort. Restarting in $TimeOutinSeconds" -NoNewLine

    While ($TimeOutinSeconds -gt 0 -and -not $host.UI.RawUI.KeyAvailable) {
        Start-Sleep -Seconds 1
        $TimeOutinSeconds --
        Write-Host –NoNewLine ",$TimeOutinSeconds"

    if ($Host.UI.RawUI.KeyAvailable -eq $false) {
        Write-Host &quot;<code>nRestarting Computer(s)...&quot;
        Restart-Computer -ComputerName $ComputerName -Force
    else {
        Write-Host &quot;</code>nRestart Aborted!&quot;


# Restart-ComputerWithDelay –TimeOutinSeconds 15 –ComputerName &quot;Demo1&quot;,&quot;Demo2&quot;

With a slightly different logic and with less lines of code, you can implement the above functionality using the Ctrl + C key combination.

Write-Host "Restarting in 30 seconds. Press CTRL-C to abort or any key to restart…"
Filed in: Columns, Tips and Tricks Tags: ,
© 6650 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: