2

I wrote a script to check the IIS service status every 15 minutes on a web server. I scheduled this script via Windows Task Scheduler.

When Im logged onto the server and manually run the script if functions coorectly. When I am not logged onto the server and execute this via at batch script, the Get-Service query does not return Running for IIS even though it is indeed up and restarts the service.

Why would this script run differently when Im physically logged onto the server vs running as a scheduled task behind the scenes?

The script is called like this: C:\Scripts\powershell.exe -File verify_status.ps1 [Service param]

############################## # Get service status ############################## if($args[0] -ne $NULL){ $serviceName = $args[0] $serverName = hostname $status = (Get-Service $serviceName).Status if ($status -ne "Running"){ sendMail "$serviceName" "$serverName" Restart-Service $ServiceName }else{ # Service is running, do nothing; } } 

=====================================

EDIT - The Get-Service returns a NULL when the script is run with no one logged on. If that helps at all.

2
  • The scheduled task run with same credentials as you log on? Commented Sep 26, 2012 at 19:06
  • @Christian - Yes, it runs with my same credentials. Commented Sep 26, 2012 at 19:41

1 Answer 1

0

Two things resolved this issue. I think the main one was changing the .bat script calling the powershell script.

I went from:

C:\Scripts\powershell.exe -File verify_status.ps1 [Service param] 

to

C:\Scripts\powershell.exe -File verify_status.ps1 "[Service param]" 

The double quotes were necessary to pass the parameter correctly to the powershell script.

I also changed the following in the powershell script itself. Im not sure if this was necessary but the combination of the two made this work:

$status = (Get-Service $serviceName).Status 

to

$status = (Get-WmiObject -ComputerName SERVERNAME -Class Win32_Service -Filter "Name='$serviceName'").State 

The Windows Task Scheduler now executes this script correctly and without error.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.