Windows Server 2008 R2 PowerShell script runs manually, but not as a scheduled task

I have a PowerShell script that runs manually using the PowerShell ISE. However, when run as a scheduled task using an administrator's credentials the task does not run with the expected results.

The script:

$request=new-object System.Net.WebClient
$request.DownloadFile("...url...", "C:\path\to\file.csv")

The administrator user has Full Control of both the script and the folder it is writing to. The URL exists and responds in a reasonable time (less than one second).

If I run the task manually the status is 0x41301 ("Currently Running") until I eventually end it. I have set the task up using both of these methods:

  1. Start a Program: C:\path\to\PS.PS1
  2. Start a Program: C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe with additional options -noninteractive -command "C:\path\to\PS.PS1"

Using option 1, the task history shows it has opened an instance of notepad.exe, but it never terminates it. Using option 2 it completes the task, but it doesn't download / create the file.

I have used Set-ExecutionPolicy Unrestricted as this is not a signed script.

How can I fix this problem?


Solution 1:

As you are running a script file instead of a script block, the parameter that you should use is -File.

Additionally, setting the execution policy using the Set-ExecutionPolicy cmdlet does not guarantee that the script is executed in that context. The effective execution policy might be overwritten by group policy (GPO). To force this on on the execution of the file use the -ExecutionPolicy parameter

The command that you are looking for is as follows

powershell.exe -ExecutionPolicy Unrestricted -NonInteractive -NoProfile -File c:\path\ps.ps1

More information of these parameters can be found here.

Solution 2:

The script file you are trying to run is not a natively trusted file. Use an ampersand before the file path to run the command:

Powershell.exe -ExecutionPolicy Unrestricted -Command { & 'C:\path\to\PS.PS1' }

Other PowerShell startup parameters can be found in PowerShell.exe Command-Line Help.