Search code examples
powershellreboot

What's the best way to monitor a server reboot?


I have a powershell script that restarts a server. I also wanted this script to monitor when the server goes down and when it comes back up. Right now I'm using the command:

   Test-Connection

Is this the right way to do it? Is there a better way to do this? Maybe through Event Viewer?

Thank you for your time


Solution

  • Here is a common scaffolding I use in situations like this:

    $maxTries = 15
    while (-not(test-connection offLinePC -Count 1 -quiet)){
        "trying again..."
        $i++
        if ($i -eq $maxTries){break;}
    }
    

    If you don't need to have a maximum number of tries, you could simplify it like this...

    while (-not(test-connection offLine -Count 1 -quiet)){
        "Waiting for `offLine ` to reboot...trying again..."
    }
    else{
        "offLine is back online!"
    }
    

    Simple Improvement

    I actually really dislike the syntax of Test-Connection, so I bake a small function into my scripts like this:

    function WaitForReboot{param($HostName)
        test-connection $HostName -Count 1 -quiet
    }
    
    while (WaitForReboot OffLinePc){
        "trying again..."
    }