如何向Windows计划任务传递参数?

Евг*_*мов 5 powershell scheduled-tasks

我需要将参数传递给使用 Windows 计划任务运行的 PowerShell 脚本。Start-ScheduledTask -TaskName "ExampleTask*"使用 cmd命令从 Azure 管道运行计划任务

计划任务图像

计划任务有这样的PS脚本:

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

echo $var
Run Code Online (Sandbox Code Playgroud)

我需要$var从 Azure DevOps 管道进行动态更改。有什么方法可以做到这一点吗?

Lev*_*SFT 4

您可以使用Set-ScheduledTaskAzure Pipeline 任务中的动态变量来更新现有的 ScheduledTask。请参阅以下步骤。

1、在azure管道中创建变量,如果是credential,则将变量类型更改为secret。见下文:我在管道中创建了UserPasswordDynamicVariable

在此输入图像描述

2、在管道中添加一个powershell任务来更新现有的ScheduledTask。

我在计划任务中设置参数如下: -NoProfile -ExecutionPolicy Bypass -File "c:\test\scheduled.ps1" -var "$(DynamicVariable)"'

请参阅 Powershell 任务中的以下脚本。

#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"
Run Code Online (Sandbox Code Playgroud)

DynamicVariable如果你想在管道中动态设置变量。您可以使用日志记录命令 "##vso[task.setvariable variable..]..

在上述 powershell 任务之前添加另一个 powershell 任务以运行以下命令:

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

  • 您可以尝试在 powershell 任务中映射秘密变量。例如,将其映射到 powershell 任务 `MyPassword = $(Password)` 中的环境变量 MyPassword,然后将环境变量 `$env:MyPassword` 传递给 $Action `New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument ' -NoProfile -ExecutionPolicy 绕过 -File "c:\test\scheduled.ps1" -var "$env:MyPassword"'`。有关详细信息,请参阅[此处](https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch#secret-variables) (2认同)