Search code examples
windowspowershellcmdscheduled-tasks

Unable to run Powershell script via CMD file


A .ps1 server can run successfully on a Windows 10 Pro server via ISE/Powershell but systematically fail if executed using a .cmd command inserted into a Windows scheduling task (or using the .cmd itself directly). Script's logs always record the same error message during these runs: *"Error: Exception calling "ExecuteQuery" with "0" argument(s): "The remote server returned an error: (400) Bad Request." MyTargetFile: "

So I assume that at least the .cmd could invoke the script.

The script is performing basic file transferring operations on a Windows 10 Pro server machine. The process within the script involves accessing Sharepoint Online via basic auth using a technical user's credentials, several data processing operations and a last step in which several output files are deposited on two shared network folders.

I have created a scheduling task and a simple .cmd file pointing towards the .ps1 resource that is used within the scheduling operations, with no other arguments required as the whole process is handled within the .ps1:

powershell -file C:\BATCH\FileName.ps1

The scheduling task has already been configured to run with the highest privileges.

I'd also add that using the .ps1 file for the scheduling task setup won't even invoke the script at all.

Is there anything else I'm missing to properly setup the scheduling task or to let the .cmd work?


Solution

  • Could be that in the user context that it's being run via the Task Scheduler that it's being caught by the execution policy.

    Easy way to check (and if confirmed avoid the issue in future) is to call your script with

    powershell -executionpolicy bypass -file C:\BATCH\FileName.ps1
    

    I've seen (though rarely) some systems only successfully run the scheduled script (via cmd, or direct in the task scheduler) if powershell.exe is called using its full file path. Presumably because within the elevated admin context it's not within the existing PATH variable perhaps.