8

I have a couple of Exchange 2010 PowerShell scripts that I'd like to run as Scheduled Tasks.

If I launch PowerShell using "Run as different user" I can run the scripts and they execute correctly.

If I schedule a task using that same user, the task stays in the Running state forever.

How can I figure out where the task is getting stuck?

For reference, here's how I enable the Exchange stuff:

. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto

And here is the ways I have tried to run the script from the Task Scheduler:

  • powershell -command "& {. 'c:\windows\script.ps1' }"
  • powershell -file 'c:\windows\script.ps1'
  • powershell -file "c:\windows\script.ps1"

All with the same result. Grr...

longneck
  • 22,793
  • 4
  • 50
  • 84
  • Commenting late to the party, but I had the same behavior. A scheduled task registered using PowerShell's `Register-ScheduledJob` never 'ended' it did end once I closed my PowerShell console and ISE. – user4317867 Jul 02 '16 at 22:48

5 Answers5

3

You either need to modify your execution policy, or specify the -ExecutionPolicy Bypass as a commandline parameter.

powershell -Command "<path to .ps1 script>" -ExecutionPolicy Bypass
TheCompWiz
  • 7,349
  • 16
  • 23
  • 1
    I added the ExecutionPolicy option to my command line parameters. No change; task still runs forever. – longneck Nov 01 '12 at 18:20
2

Not sure if this is how you are doing it, but when I am running PowerShell scripts via task scheduler I use the "Start a program" action and select powershell and then add the arguments from there. That might be what you are doing here, but it's kind of unclear. Here's a screenshot: enter image description here

Per TheCompWiz execution policy might also be an issue.

znewman
  • 165
  • 8
0

I had the same problem. In my case the solution was to specify the "start in" directory (my script would read the contents of a file which it wouldn't find because I didn't specify the full path to the file).

Azimuth
  • 101
0

I had the same problem and the comment by "user279399" to use the taskkill command was super helpful, just needed modification. Here's my solution at the end of the argument syntax

taskkill /f /fi "USERNAME eq domain\exchadmin" /im powershell.exe

This command kills only the powershell session that's running under that user account. It is best practice to have a separate exchange admin account for running scheduled tasks.

Leon B
  • 1
-3

Try add to the end of your script [taskkill /f /im "powershell.exe"] this will kill all "powershell.exe" processes. I don't know how to kill the current power-shell process (equivalent to [cmd.exe /c]). But it will do the trick.

  • And what if there were another powershell scripts running, probably doing something important? Would you just kill these processes without asking? On a production environment? As a routine? Seriously?! – Esa Jokinen Apr 01 '15 at 08:10