by pitccorp01 at 2013-04-08 06:45:26
Hi,by happysysadm at 2013-04-08 06:52:32
I am trying to write a powershell script to check if a service has started after a server reboot. The script decides whether the service has started or not. If the service has started, send a message "Service is running".If the service has not started, the script waits 30 seconds and rechecks the status of the sevice continuously until the service has started.
Here is my problematic code.if ((get-service AGENT -computername myserver |select-object status | format-table -hide -autosize) -eq "Stopped") {
write-host "Stopped"
do {
Start-Sleep 30
RECHECK="get-service AGENT -computername myserver |select-object status | format-table -hide -autosize"
}
while (RECHECK="get-service AGENT -computername myserver |select-object status | format-table -hide -autosize")
}
else {
write-host "Running"
}
Thanks in advance for your assistance,
Anthony
Hi Anthony,by pitccorp01 at 2013-04-08 07:25:31
First thing, the ‘=’ sign is an assignment operator in Powershell.
Don’t use it for string comparison in your while loop. In your case I would use -‘eq’.
Carlo
I have made the recommended change using "-eq" in the while loop. I have not received any new errors; however, the script is not analyzing whether the serivce has started or not. I am getting the message "Running" whether the service has stooped or starting. Any ideas?by happysysadm at 2013-04-08 07:32:40
Hi,by pitccorp01 at 2013-04-08 08:12:09
that was only the first thing to notice.
now have a look at this:
[code2=powershell]if ((get-service agent).status -eq "Stopped") {
do {
write-host "Stopped"
Start-Sleep 3
$RECHECK=(get-service agent).status
}
while ($RECHECK -notmatch 'Running')
}
else {
write-host "Running"
}[/code2]
Does it work better? I moved a few thing around. You can also put the service name into a variable.
Remember that vars start with a dollar sign.
Let me know if it work.
Carlo
This works as expected. Nice job! Thanks Carlo