Restart servers with check of services?

This topic contains 5 replies, has 2 voices, and was last updated by  Dave Wyatt 3 years, 7 months ago.

  • Author
    Posts
  • #14403

    Jay B
    Participant

    Hello

    I would like to ask for some help on getting a script together that will reboot a list of servers and have the script check to verify that a couple of services have started after the reboot.

    The catch to this is that I want to have the script reboot the first server, check for a service, then if that's running, proceed to reboot 8 more servers at the same time, and verify that a service is running after each server comes back online.

    To be honest, I am entirely lost on how to do this and I am trying to figure it out, but I was hoping to use it for a job tonight as part of a system update.

    Thanks,
    Jay

  • #14407

    Dave Wyatt
    Moderator

    The Restart-Computer cmdlet has some of this functionality built-in, as of PowerShell 3.0. See http://technet.microsoft.com/en-us/library/hh849837.aspx for details. You could do something like this:

    $serviceToCheck = 'bits'
    
    foreach ($server in $servers)
    {
        Restart-Computer -ComputerName $server -Wait -For Wmi
    
        while ((Get-WmiObject -ComputerName $server -Class Win32_Service -Filter "Name = '$serviceToCheck'").State -ne 'Running')
        {
            Start-Sleep -Seconds 5
        }
    }
    

    This sample code is not very robust, though. It will wait forever for the computers to restart, or for the service to be running; there's no code to time out or handle other errors.

  • #14421

    Jay B
    Participant

    Thanks, I'll try to add more to this, I'm not sure how as I'm just starting the books that were suggested.

    Will this reboot the servers in "parallel" or is this 1 at a time?

  • #14422

    Dave Wyatt
    Moderator

    That code would be one at a time. The foreach loop won't proceed to the next server on the list until Restart-Computer returns and the service is in a Running state again.

  • #14423

    Jay B
    Participant

    Ok, thanks. So I have to do something else to reboot all of them at the same time, then check the service status after the restart.

    What's the best way to do it if I have the list of servers in a file, the service name could be in a file or in the script, and then restart them all, and then check the service status, followed by sending an email?

    I'm wondering how to do this in the most efficient manner?

    Thank you again,
    Jay

  • #14425

    Dave Wyatt
    Moderator

    Sorry, I misread your original post. I thought you wanted the servers rebooted one at a time. Restart-Computer can be passed an array of strings for the ComputerName, and (in conjunction with the -Wait and -For Wmi arguments) will wait until all of them are back online. Then you can use WMI to check the services, as I did in the example code.

You must be logged in to reply to this topic.