Powershell 如何将参数传递给Windows计划任务?

Powershell 如何将参数传递给Windows计划任务?,powershell,scheduled-tasks,Powershell,Scheduled Tasks,我需要将参数传递给使用Windows计划任务运行的PowerShell脚本。 计划任务使用cmdStart ScheduledTask-TaskName“ExampleTask*”命令从Azure管道运行 计划任务的PS脚本如下所示: param( [Parameter(Mandatory = $true)] $var ) echo $var 我需要从Azure DevOps管道动态更改$var。 有什么方法可以做到这一点吗?像这样配置它 程序/脚本:%SystemRoot

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

计划任务的PS脚本如下所示:

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

echo $var
我需要从Azure DevOps管道动态更改
$var

有什么方法可以做到这一点吗?

像这样配置它

程序/脚本:%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe

参数:-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)
当路径或参数中有空格时,可以使用以下任何引号变体:

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

-c "& ""c:\script.ps1""" -var 'the param'
在论据中引用

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

您可以使用
Set ScheduledTask
使用Azure管道任务中的动态变量更新现有的ScheduledTask。请参见以下步骤

1、在azure管道中创建变量,如果是凭据,则将变量类型更改为secret。请参见以下内容:我在管道中创建了用户密码动态变量

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"
如果要在管道中动态设置变量
DynamicVariable
。您可以使用
“##vso[task.setvariable…”

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


echo“##vso[task.setvariable=DynamicVariable]newValue“

嗨!感谢您的回答,我想直接从Azure管道任务更改变量,该任务使用Start ScheduledTask命令触发已经存在的ScheduledTask。但据我所知,在你的方法中,你直接在Arguments字段中设置变量值,但这有点不安全,因为如果我想在这里传递一些凭据,它们将是可见的。嗨,谢谢你的回复,我喜欢这种方法,但是,有没有一些方法可以在运行SchedulerTask的PS脚本中使用Azure管道中的秘密变量?例如,如果我在PS script中使用Password,您只需将azure管道中定义的秘密变量(例如Password)传递给
$Action
New ScheduledTaskAction-Execute“PowerShell.exe”-Argument'-NoProfile-ExecutionPolicy Bypass-File“c:\test\scheduled.ps1”-var“$(Password)”
yeah,但是当我像这样传递secret变量时,它会在TaskScheduler Actions部分可见。您可以尝试在PowerShell任务中映射secret变量。例如,将其映射到powershell任务中的环境变量MyPassword
MyPassword=$(Password)
,然后将环境变量
$env:MyPassword
传递到$Action
新的ScheduledTaskAction-执行“powershell.exe”-参数“-NoProfile-执行策略旁路-文件“c:\test\scheduled.ps1”-var“$env:MyPassword”
。有关更多信息,请参阅