我想使用Powershell在Windows计划任务的“触发器”选项卡中设置选项“如果运行时间超过则停止任务”的值。
已经尝试使用/ DU开关,但是它不起作用。
如果需要任何其他信息,请告诉我。
@TobyU:我也尝试了您的建议,但未设置所需的值。以下是屏幕截图,供您参考。
谢谢。
答案 0 :(得分:2)
您可以一次为整个任务设置它:
$task = Get-ScheduledTask -TaskName "MyTask"
$task.Settings.ExecutionTimeLimit = "PT3H"
Set-ScheduledTask $task
在上述示例中3小时后停止。
这是您仅针对特定触发器设置的方式:
$task = Get-ScheduledTask -TaskName "MyTask"
$task.Triggers[0].ExecutionTimeLimit = "PT3H"
Set-ScheduledTask $task
Triggers[0]
是您要调整的特定触发器,因为$task.Triggers
返回一个数组,其中包含特定任务的所有可用触发器对象。
答案 1 :(得分:1)
我使用的是 Windows 10 专业版和 PowerShell 7,以下对我来说效果很好。
创建新任务:
# Creating a task with multiple triggers and different execution limits
$taskName = "MyTask"
$trigger1 = New-ScheduledTaskTrigger -Once -At "2021-05-10 12:00:00"
$trigger1.ExecutionTimeLimit = "PT20M"
$trigger2 = New-ScheduledTaskTrigger -Once -At "2021-05-13 17:30:30"
$trigger2.ExecutionTimeLimit = "PT50M"
$taskTriggers = @(
$trigger1,
$trigger2
)
$taskAction = New-ScheduledTaskAction -Execute "notepad.exe"
Register-ScheduledTask -TaskName $taskName -Trigger $taskTriggers -Action $taskAction
为了更新现有任务的触发器,@TobyU 提出的解决方案对我来说效果很好:
# Updating execution limits of a task that already exists
$taskName = "MyTask"
$task = Get-ScheduledTask -TaskName $taskName
$task.Settings.ExecutionTimeLimit = "PT30S" # Global limit
$task.Triggers[0].ExecutionTimeLimit = "PT10S" # Limit for trigger 1
$task.Triggers[1].ExecutionTimeLimit = "PT15S" # Limit for trigger 2
Set-ScheduledTask $task
但是,您也可以用新触发器完全替换旧触发器:
# Completely replacing all triggers with new one of an already existing task
$taskName = "MyTask"
$trigger = New-ScheduledTaskTrigger -Once -At "2021-05-17 17:17:17"
$trigger.ExecutionTimeLimit = "PT42M"
Set-ScheduledTask -TaskName $taskName -Trigger $trigger
答案 2 :(得分:0)
Invoke-Command -ComputerName Computername -Scriptblock
{
$action = New-ScheduledTaskAction -Execute 'C:\app.exe” '
$trigger = New-ScheduledTaskTrigger -Daily -At 10am -RandomDelay (New-TimeSpan - Minutes 480)
$principal = New-ScheduledTaskPrincipal -GroupID "BUILTIN\Administrators" -
RunLevel Highest
Register-ScheduledTask -Action $action -Trigger $trigger -Principal $principal -
TaskName "Schedule_task_name" -Description "Task Description"
$Task = Get-ScheduledTask -TaskName "Schedule_task_name"
$Task.Triggers[0].ExecutionTimeLimit= "PT30M"
Set-ScheduledTask $Task
}