How to pass parameters to Windows Scheduled Task?

Viewed 5528

I need to pass parameters to PowerShell script that runs using Windows Scheduled Task. Scheduled Task runs from Azure pipeline using cmd Start-ScheduledTask -TaskName "ExampleTask*" command

Scheduled Task image

Scheduled Task has PS script like this:

param(
    [Parameter(Mandatory = $true)]
    $var
)

echo $var

And I need to change $var dynamically from Azure DevOps pipeline. Are there any ways to do this?

2 Answers

You can use Set-ScheduledTask to update the existed ScheduledTask with dynamic variables from Azure Pipeline task. See below steps.

1, Create variables in your azure pipeline, change the variable type to secret if it is credential. See below: i created User, Password, DynamicVariable in the pipeline

enter image description here

2, Add a powershell task in your pipeline to update your existed ScheduledTask.

I set the Arguments in my scheduled task as this: -NoProfile -ExecutionPolicy Bypass -File "c:\test\scheduled.ps1" -var "$(DynamicVariable)"'

See below script in the Powershell task.

#update the Argument with variable defined in the pipeline $(DynamicVariable)
$Action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument '-NoProfile -ExecutionPolicy Bypass -File "c:\test\scheduled.ps1" -var "$(DynamicVariable)"' 

#update the scheduled task
Set-ScheduledTask -Password "$(Password)" -User "$(User)" -TaskName "PipelineTask" -Action $Action

Start-ScheduledTask -TaskName "MyTask"

If you want to set the variable DynamicVariable dynamically in the pipeline. You can use logging commands "##vso[task.setvariable variable..]...

Add another powershell task before above powershell task to run below commands:

echo "##vso[task.setvariable variable=DynamicVariable]newValue"

Configure it like this;

Program/Script : %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe

Arguments : -c "C:\script.ps1 -var thevalue"

script.ps1 :

    param(
        [Parameter(Mandatory = $true)]
        $var
    )
    
    [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    [System.Windows.Forms.Messagebox]::Show("This is the Message text : " + $var)

When there are spaces in path or arguments, any of the following quotation variations could be used;

-c "& 'c:\script.ps1'" -var 'the param'

-c "& ""c:\script.ps1""" -var 'the param'

For quotes in arguments;

-c "& ""c:\script.ps1""" -var 'the x\"x''param'
-c "& ""c:\script.ps1""" -var 'the x"""x''param'
Related