Running powershell script through Windows Task Scheduler
2014-06
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.
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:
- Run the second script using a UNC path (and ensure that the system account has access to the UNC path)
- 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). - Safest option: make a copy of the file locally.
Please check this one out from stackoverflow, seems pretty similar case: How can I convince powershell (run through task scheduler) to find my network drive?
The command you tried from a batch file was wrong.
Try this command, and remember to keep the quotations.
powershell.exe -file ". 'C:\Users\Robin\Documents\script.ps1'"
I want to schedule a powershell script to run on my windows 7 system everyday with admin priviliges.
How do I do so?
You can use schtasks
, from an elevated CMD prompt.
eg.
schtasks /create /tn "My Task Name" /ru Administrator /sc daily /sd 28/05/2011 /st 14:00 /tr "powershell.exe -noprofile -executionpolicy RemoteSigned -file %MyPATH%\MyTaskScript.ps1"
This would run the script at 14:00 every day.