Writing a loop for checking services after reboot

This topic contains 0 replies, has 1 voice, and was last updated by Profile photo of Forums Archives Forums Archives 5 years, 6 months ago.

  • Author
    Posts
  • #5787

    by pitccorp01 at 2013-04-09 08:38:27

    Hi,

    I am trying to write a script to parse through an input file with server names and check if a service has started or not after a reboot. If the service has started, sent a message "Serivce is running" if not, wait 30 seconds and check again until the service has started, and then send message "Service is now running".

    Here is an excerpt of my code:

    foreach ($machine in cat $INPUT_FILE) {
    if ((get-service -computername $machine *Agent*).status -eq "Stopped") {
    do {
    write-host "Service has Stopped"
    Start-Sleep 30
    $RECHECK=(get-service -computername $machine *Agent*).status
    }
    while ($RECHECK -notmatch 'Running')
    }
    else {
    $LOG_STAMP=get-date -uformat "%d-%m-%Y %H:%M:%S: "
    Add-Content -Path "$OUTPUT_LOG" -Value "$LOG_STAMP $machine agent process is now in Running status"
    }
    }

    The code works for detecting the "running" service but not so well when the service has not "stopped".

    Thanks in advance for the assistance,
    Anthony

    by robertskinner at 2013-04-09 10:02:18

    Do you get any error's when it's not running?

    One possible reason The WMI may not be reporting in for the service depending on how soon you are running the script after the server has booted. I have in one script for a simular type situation something simular. Why not check if it's running first in your statement, since all you are doing is sending the message. This way, any other state can be handled as not running.

    by mjolinor at 2013-04-09 11:16:43

    You may not be getting the results you expect becaue of the way the loop is written.
    You're looping through a collection of computers, checking the service status on each one, and sleeping for 30 seconds if it's stopped. That means it's going to sleep when it hits the first machine that has an Agent service in the Stopped state, before it checks any of the rest of the machines in the list.

    By the time the sleep timer expires, the rest of them have probably already restarted, and you'll only see the first one reported.

You must be logged in to reply to this topic.