#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: ,

One Response to "#PSTip Offer Delayed Restart with Abort Functionality"

  1. Pete says:

    when I run the Restart-ComputerWithDelay function I get the following error:

    Press any key to abort. Restarting in 10,9,8,7,6,5,4,3,2,1,0Exception calling “FlushInputBuffer” with “0” argument(s): “The method or operation is not implemented.”
    At line:23 char:40
    + $Host.UI.RawUI.FlushInputBuffer <<<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Leave a Reply

Submit Comment

© 2018 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: