Windows – Running powershell script through Windows Task Scheduler

powershellwindows 7windows task scheduler

I'm trying to run a simple PS1 powershell script from the Task Scheduler. The task's Actions settings are Program: powershell and Add arguments: -executionpolicy bypass -file C:\Users\Robin\Documents\script.PS1.

The objective script.PS1 is accessed ok but a line within it (a call to another script: Rscript Z:\rscript.R) fails with the message:

Fatal error: cannot open file Rscript Z:\rscript.R
'rscript.R': no such file or directory

If I run the same line manually in Powershell it works ok. Moreover the following runs fine as a Run command: powershell -executionpolicy bypass -file C:\Users\Robin\Documents\script.PS1, which suggests the problem is in Task Scheduler. The task is set to run with highest privileges. I'm stumped.

Very grateful for assistance.

Best Answer

I'm assuming that Z: is a network drive.

Scheduled jobs are (usually) run under a System account. Network drives aren't usually mapped for System. Even if you change it to run under your credentials (or any specific user credential), you just can't count on network shares being accessible. You'll need to either:

  1. Run the second script using a UNC path (and ensure that the system account has access to the UNC path)
  2. Map the network drive early on in your script (in PowerShell 3 you could use New-PSDrive, but), the simplest way is to run the NET USE Z: \\SERVER\SHARE command. Of course, you might need to add user credentials: password /USER:domain\user and you could also try adding /SAVECRED /PERSISTENT:YES and running that command once and hoping it sticks (but I'd still test-path and remap it if that's an option).
  3. Safest option: make a copy of the file locally.
Related Question