#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 {
    Param(
        [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 {
        $Host.UI.RawUI.FlushInputBuffer()
        Write-Host &quot;</code>nRestart Aborted!&quot;
    }
}

Restart-ComputerWithDelay

# 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…"

About the author: Manoj Ravikumar

Manoj Ravikumar Nair works with Microsoft Services Global Delivery as Consultant on Core-IO technologies. In his current role, he enables Microsoft Premier Customers to design, position, sell and deploy Microsoft Platforms and Infrastructure Solutions for customers by providing end to end consulting, He has delivered many technical webcasts/talks/Practice Accelerator Workshops in North America on Microsoft Windows Server and Client Technologies, Exchange Server, System Center Suite, Forefront UAG, PowerShell and Virtualization to educate, evangelize and create awareness on new Microsoft technologies and drive adoption. He absolutely LOVES technical training and is a Microsoft Certified Trainer (MCT) since January 2008 along with other Microsoft and Citrix Certifications. He is passionate about PowerShell and blogs about it on his blog http://blogs.technet.com/b/manojnair. You can follow him on twitter@ http://twitter.com/#!/powershellpro

Related Posts

%d bloggers like this: