Rebooting in an automated patch process using Powershell

This post is a part of my series on Patching SQL Server AG using SCCM and Powershell
Please read this post for the complete overview

When you’ve automated your patching process, somewhere inside this process there is going to be a reboot somehow. If, after your reboot, you need to finish what you’ve started or check the health of your Availability Group, you need to know when the server is back online.

With powershell it’s fairly easy to reboot a computer using the Restart-Computer cmdlet:

Restart-Computer -ComputerName $Server -Force

It’s more tricky though to determine when a server is back online.
One option is using the Test-Connection cmdlet. In the following example we keep trying when we get no response back and wait for 15 seconds between the retries:

while ((Test-Connection -ComputerName $Server -Count 1 -Quiet) -ne $true) {
     Start-Sleep -Seconds 15 

But….what if the server is still in the process of shutting down?

Or.. what if, the server responds to a ping, but is still installing updates AFTER the reboot:

Afbeeldingsresultaat voor installing updates

You can’t do anything on this server while this is happening. You won’t even see this screen when everything is done remotely. Your script continues, waits and will fail eventually.

Another option is to use WMI for this.

Windows updates the “Lastbootuptime” when the computer is fully restarted and “usable”. You can get this information by querying the win32_operatingsystem class:

In the following example, we query this information and compare it with the current timestamp. If there is a difference, then the server is fully rebooted:

$CurrentTimeStamp = (GET-DATE)
[datetime]$LastRebootTime = Get-CimInstance -ClassName win32_operatingsystem -ComputerName $Server | select-object lastbootuptime -ExpandProperty Lastbootuptime
        Restart-Computer -ComputerName $Server -Force
        $Diff = $LastRebootTime - $CurrentTimeStamp
        while ($Diff.TotalSeconds -lt 0) {
            try {
                [datetime]$LastRebootTime = Get-CimInstance -ClassName win32_operatingsystem -ComputerName $Server -ErrorAction SilentlyContinue | select-object lastbootuptime -ExpandProperty Lastbootuptime
                $Diff = $LastRebootTime - $CurrentTimeStamp
                Start-Sleep 5
            Catch {
              #no catch code

A much more reliable way to check when a server is fully rebooted!

I hope my guide on Rebooting in an automated patch process using Powershell was helpful—feel free to leave questions in the comments!

If the task still seems a bit daunting, book a call with Data Masterminds. We have the expertise to execute this and other SQL Server management and troubleshooting tasks to save you the headache.

One thought to “Rebooting in an automated patch process using Powershell”

Leave a Reply

Your email address will not be published. Required fields are marked *