PowerShell script running from scheduled task: action failed to start, directory name invalid

1

I have a Windows Server 2012 R2 server running a scheduled task with three actions, each running PowerShell scripts:

actions

Each of these actions "starts in" the relevant (and correct) directory:

single action

Originally, the third action - ApplyABPs - was set up in exactly the same way as the other two, e.g. a simple "start in" folder and then .\ApplyABPs.ps1 as the argument. This worked as intended.

I wanted to add some logging to the latter script, so I added the following code to dot-source my shared FunctionsLibrary.ps1 file, create a log file and write to it:

# Call functions file...
. (Join-Path "C:\scripts\" FunctionLibrary.ps1)

# Create a log file
$LogFile = Create-Log -Location $LogfileLocation

Write-Log -Important -Text "==== ApplyABPs.ps1 ====="

The additions to the ApplyABPs script and this FunctionLibrary.ps1 script work in other files.

If I run this ApplyABPs.ps1 script from the PowerShell ISE, it works as intended - creates the log file and writes to it.

However, when I then try to run the Scheduled Task, the first two actions run as usual but the third action fails:

task failure

That code doesn't give me a lot of detail but the Last Run Result at the top of Task Scheduler says The directory name is invalid. (0x8007010B).

So... for testing purposes, I tried adding the same FunctionLibrary.ps1 and in-script code amendments to the other two actions. The Task Scheduler then failed immediately and returned the same error for the very first action.

When I then take the code back out, the actions work.

I tried changing the way the Scheduled Task calls PowerShell (hence the -executionpolicy bypass, -noprofile and -file parameters in the top screenshot) but this has made no difference.

Based on the directory invalid error message, I'm wondering if PowerShell - when called by the Scheduled Task - is unable to access the dot-sourced file, or something along those lines?

If anyone could shed any light on this specific error, or give an insight into how Task Scheduler calls PowerShell (and the directories/relativity it uses), that would be ideal.

windows
windows-server-2012-r2
powershell
scheduled-task
task-scheduler
asked on Server Fault May 30, 2018 by turbonerd • edited May 30, 2018 by SturdyErde

1 Answer

4

Use the following syntax to run a PowerShell script in task scheduler:

Program/script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Add arguments: -NoLogo -Noninteractive -Noprofile -Command "&{C:\ScriptFolder\get-LicensingInputFromAD.ps1}"

And use the full path\filename for each .ps1 file in your task arguments field.

answered on Server Fault May 30, 2018 by SturdyErde • edited May 30, 2018 by SturdyErde

User contributions licensed under CC BY-SA 3.0