powershellparameter-passingwindows-task-scheduler

Powershell Script Will not Run upon Open or Pass Parameter from Task Scheduler


I call the PowerShell application in the Task Scheduler Program/Script prompt as follows:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe

I then call the executable script in the Add arguments prompt as follows:

C:\1hwebster\PSISE_Scripts\OpenExcelFile.ps1

This successfully opens my script in a PowerShell window. However, it does not run the script.

I also need to pass a parameter from task scheduler to the script, for which I have tried the -File method:

-File "C:\1hwebster\PSISE_Scripts\OpenExcelFile.ps1" fpathfname 'C:\1hwebster\VBA\DailyEconomicCalendar.xlsm'

This reads the fpathfname parameter as a second file and criticizes my syntax. enter image description here

I have also tried the -Command method:

-Command "& C:\1hwebster\PSISE_Scripts\OpenExcelFile.ps1 -fpathfname 'C:\1hwebster\VBA\DailyEconomicCalendar.xlsm'"

This returns an Error processing arguments: There is no option with the following name: Command. enter image description here

I have tried all iterations of quotes and single quotes around the -File and -Command contents with no success as well. What do I need to type to successfully run the PowerShell script and pass the parameter from Task Scheduler?


Solution

  • Windows 10 64-bit. PowerShell 5.1

    How to pass arguments from a Windows scheduled task to a PowerShell script.

    Create %USERPROFILE%\Desktop\1.ps1 with the following content:

    Write-Output "
    All the arguments are: $args"
    Write-Output "    The first argument is: " $args[0]
    Write-Output "    The second argument is: " $args[1]
    cmd /c pause 
    exit 
    

    Build your scheduled task:

    A stopped task will sometimes leave behind an instance of conhost.exe. If it is not killed the task might fail. Make the following command the first action of your task:

    taskkill /f /im conhost.exe 
    

    If there are no spaces and / or quotes in your argument / s you do not have to quote the argument / s.

    powershell %USERPROFILE%\Desktop\1.ps1 Argument1 Argument2
    

    If there are spaces and / or quotes in your argument / s you have to single quote the argument / s.

    powershell %USERPROFILE%\Desktop\1.ps1 'Argument One' 'Argument Two' 
    powershell %USERPROFILE%\Desktop\1.ps1 '"ArgumentOne"' '"ArgumentTwo"' 
    

    Copy and paste the entire command into a new action in the "Program/script:" box and click OK. Windows 10 Task Scheduler will ask you if you want to split the paste between "Program/Script" and "Add arguments". Click Yes.

    screenshot paste command into new action

    References: