PowerShell:日常触发和重复间隔的计划任务

发布于 2025-01-23 03:21:33 字数 1812 浏览 0 评论 0原文

我似乎无法弄清楚如何创建每天触发的新计划任务并每30分钟重复一次。我一直在盘旋。

以下所有内容都适用于设置我想要的任务,但仅触发一次。

#Credentials to run task as
$username = "$env:USERDOMAIN\$env:USERNAME" #current user
$password = "notmypass"

#Location of Scripts:
$psscript = "C:\test\test.ps1"
$Sourcedir ="C:\testsource\"
$destdir = "C:\testdest\"
$archivepassword = "notmypass"


####### Create New Scheduled Task
$action = New-ScheduledTaskAction -Execute "Powershell" -Argument "-WindowStyle Hidden `"$psscript `'$sourcedir`' `'$destdir`' `'$archivepassword`'`""
$trigger = New-ScheduledTaskTrigger -Once -At 7am -RepetitionDuration  (New-TimeSpan -Days 1)  -RepetitionInterval  (New-TimeSpan -Minutes 30)
$settings = New-ScheduledTaskSettingsSet -Hidden -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RunOnlyIfNetworkAvailable
$ST = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings
Register-ScheduledTask EncryptSyncTEST -InputObject $ST -User $username -Password $password

如果我将-once更改为-daily我将失去-repeTitionInterval flags。而且,如果我回到注册后每天将任务更新为每天,它会擦拭重复触发器。

这不是一种罕见的调度方法,并且可以通过任务调度程序UI轻松应用。我觉得这可能很简单,但我缺少它。

任何帮助都将受到赞赏。

编辑:解决重复问题。帖子中的问题“ powerShell v3 new-jobtrigger每天都会重复 “也是如此。但是,正如我之前评论的那样,没有一个答案解决这个问题。标记的答案完全可以做到我在这里已经拥有的东西,它可以用-Once触发器设置任务,然后将其更新以每5分钟重复1天。在第一天之后,该任务将永远不会再次触发。它不会解决每天触发任务的问题,直到下一个触发为止。

该帖子上的其他三个答案也没有解决这个问题。我不知道为什么要标记它,因为它不正确。在发布此问题之前,我完全探索了这些答复。随着该帖子已经老化并被标记为回答,我创建了这个问题。

注意:我找到了一个解决方法,但不是一个很棒的方法。目前,使用PowerShell定义自定义触发器的最简单方法是操纵计划的任务XML并使用regissn> register-scheduledtask直接导入它。

I cant seem to figure out how to create a new scheduled task that is triggered daily and repeats every 30 minutes. I have been going in circles.

Everything about this below works for setting the task I want, but only triggered once.

#Credentials to run task as
$username = "$env:USERDOMAIN\$env:USERNAME" #current user
$password = "notmypass"

#Location of Scripts:
$psscript = "C:\test\test.ps1"
$Sourcedir ="C:\testsource\"
$destdir = "C:\testdest\"
$archivepassword = "notmypass"


####### Create New Scheduled Task
$action = New-ScheduledTaskAction -Execute "Powershell" -Argument "-WindowStyle Hidden `"$psscript `'$sourcedir`' `'$destdir`' `'$archivepassword`'`""
$trigger = New-ScheduledTaskTrigger -Once -At 7am -RepetitionDuration  (New-TimeSpan -Days 1)  -RepetitionInterval  (New-TimeSpan -Minutes 30)
$settings = New-ScheduledTaskSettingsSet -Hidden -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RunOnlyIfNetworkAvailable
$ST = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings
Register-ScheduledTask EncryptSyncTEST -InputObject $ST -User $username -Password $password

If I change -Once to -Daily I lose the -RepetitionInterval flags. And if I come back to update the task to daily after registering it, it wipes the repeating trigger.

This isn't an uncommon scheduling method, and is easily applied through the task scheduler UI. I feel like it is probably simple but I am missing it.

Any help is appreciated.

EDIT: Addressing the duplicate question. The question in the post "Powershell v3 New-JobTrigger daily with repetition" is asking the same. But as I commented earlier, none of the answers solve the issue. The marked answer does exactly what I already have here, it sets a task with a -Once trigger, then updates it to repeat every 5 minutes for 1 day. After the first day that task will never be triggered again. It does not address the issue of triggering a task everyday with repetition and duration until the next trigger.

The other three answers on that post are also not addressing the question. I do not know why it was marked answered, because it is not correct. I fully explored those replies before I posted this question. With that post having aged and being marked as answered I created this question.

Note: I have found a workaround, but not a great one. At current it seems the easiest way to define custom triggers using powershell is to manipulate the Scheduled Task XML and import it directly using Register-ScheduledTask

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

深陷 2025-01-30 03:21:33

创建基本触发器:

$t1 = New-ScheduledTaskTrigger -Daily -At 01:00

创建辅助触发器(省略-repeTitionDuration对于无限期的持续时间;请确保使用相同的-at参数):

$t2 = New-ScheduledTaskTrigger -Once -At 01:00 `
        -RepetitionInterval (New-TimeSpan -Minutes 15) `
        -RepetitionDuration (New-TimeSpan -Hours 23 -Minutes 55)

从次级插入重复对象,并插入它进入基本触发器:

$t1.Repetition = $t2.Repetition

鲍勃是你的叔叔:

New-ScheduledTask -Trigger $t1 -Action ...

Create base trigger:

$t1 = New-ScheduledTaskTrigger -Daily -At 01:00

Create secondary trigger (omit -RepetitionDuration for an indefinite duration; be sure to use the same -At argument):

$t2 = New-ScheduledTaskTrigger -Once -At 01:00 `
        -RepetitionInterval (New-TimeSpan -Minutes 15) `
        -RepetitionDuration (New-TimeSpan -Hours 23 -Minutes 55)

Take repetition object from secondary, and insert it into base trigger:

$t1.Repetition = $t2.Repetition

Bob's your uncle:

New-ScheduledTask -Trigger $t1 -Action ...
音盲 2025-01-30 03:21:33

尽管用于计划任务触发器的PowerShell接口受到限制,但事实证明,如果将RepetitionDuration设置为[System.TimesPan] :: Maxvalue,则会导致持续时间”无限期”。

$trigger = New-ScheduledTaskTrigger `
    -Once `
    -At (Get-Date) `
    -RepetitionInterval (New-TimeSpan -Minutes 5) `
    -RepetitionDuration ([System.TimeSpan]::MaxValue)

在Windows Server 2012 R2(PowerShell 4.0)上测试

While the PowerShell interface for scheduled task triggers is limited, it turns out if you set the RepetitionDuration to [System.TimeSpan]::MaxValue, it results in a duration of "Indefinitely".

$trigger = New-ScheduledTaskTrigger `
    -Once `
    -At (Get-Date) `
    -RepetitionInterval (New-TimeSpan -Minutes 5) `
    -RepetitionDuration ([System.TimeSpan]::MaxValue)

Tested on Windows Server 2012 R2 (PowerShell 4.0)

辞取 2025-01-30 03:21:33

这是一种在PowerShell(我的机器上的V5)中创建计划的任务的方法一天的。因此,它将无限期地运行。我相信这是一种出色的方法,而不是我之前评论的, ([timespan] :: maxvalue)正如我之前评论的,因为触发器将在任务调度程序中显示为:

每天上午12:00 - 触发后,每30分钟重复1天。

而不是使用-Once -at -at 12am导致触发器中注册的任务注册的日期,而是将触发器创建为简单-dedaily -daily -at am code注册任务,然后访问任务触发属性的其他属性;

$action = New-ScheduledTaskAction -Execute <YOUR ACTION HERE>
$trigger = New-ScheduledTaskTrigger -Daily -At 12am
$task = Register-ScheduledTask -TaskName "MyTask" -Trigger $trigger -Action $action
$task.Triggers.Repetition.Duration = "P1D" //Repeat for a duration of one day
$task.Triggers.Repetition.Interval = "PT30M" //Repeat every 30 minutes, use PT1H for every hour
$task | Set-ScheduledTask
//At this point the Task Scheduler will have the desirable description of the trigger.

Here is a way of creating a scheduled task in Powershell (v5 on my machine, YMMV) that will start at 12AM every day, and repeat hourly for the rest of the day. Therefore it will run indefinitely. I believe this is a superior approach vs setting -RepetitionDuration to ([timespan]::MaxValue) as I commented earlier, as the trigger will show up in the Task Scheduler as:

At 12:00 AM every day - After triggered, repeat every 30 minutes for a duration of 1 day.

Rather than the date on which the task was registered appearing in the trigger as approaches that use -Once -At 12am result in, create the trigger as a simple -Daily -At 12am, register the task then access some further properties on the tasks Triggers property;

$action = New-ScheduledTaskAction -Execute <YOUR ACTION HERE>
$trigger = New-ScheduledTaskTrigger -Daily -At 12am
$task = Register-ScheduledTask -TaskName "MyTask" -Trigger $trigger -Action $action
$task.Triggers.Repetition.Duration = "P1D" //Repeat for a duration of one day
$task.Triggers.Repetition.Interval = "PT30M" //Repeat every 30 minutes, use PT1H for every hour
$task | Set-ScheduledTask
//At this point the Task Scheduler will have the desirable description of the trigger.
煮酒 2025-01-30 03:21:33

我敢肯定,必须有更好的方法,但这是我目前的解决方法。

我用想要的触发器创建了一个任务,然后抓住了它生成的XML。

在下面,我正在创建任务,然后将XML拉动为新任务,更换触发器,然后取消登录任务并将其重新注册,并使用更新的XML进行注册。

从长远来看,我可能只将完整的XML文件用于任务并根据需要替换字符串,但这暂时可行。

#Credentials to run task as
$username = "$env:USERDOMAIN\$env:USERNAME" #current user
$password = "notmypass"

#Location of Scripts:
$psscript = "C:\test\test.ps1"
$Sourcedir ="C:\testsource\"
$destdir = "C:\testdest\"
$archivepassword = "notmypass"

####### Create New Scheduled Task
$action = New-ScheduledTaskAction -Execute "Powershell" -Argument "-WindowStyle Hidden '$EncryptSync' '$sourcedir' '$destdir' '$archivepassword'"
$trigger = New-ScheduledTaskTrigger -Once -At 7am -RepetitionDuration  (New-TimeSpan -Days 1)  -RepetitionInterval  (New-TimeSpan -Minutes 30)
$settings = New-ScheduledTaskSettingsSet -Hidden -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RunOnlyIfNetworkAvailable
$ST = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings
Register-ScheduledTask "EncryptSyncTEST" -InputObject $ST -User $username -Password $password


[xml]$EncryptSyncST = Export-ScheduledTask "EncryptSyncTEST"
$UpdatedXML = [xml]'<CalendarTrigger xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><Repetition><Interval>PT30M</Interval><Duration>P1D</Duration><StopAtDurationEnd>false</StopAtDurationEnd></Repetition><StartBoundary>2013-11-18T07:07:15</StartBoundary><Enabled>true</Enabled><ScheduleByDay><DaysInterval>1</DaysInterval></ScheduleByDay></CalendarTrigger>'
$EncryptSyncST.Task.Triggers.InnerXml = $UpdatedXML.InnerXML

Unregister-ScheduledTask "EncryptSyncTEST" -Confirm:$false
Register-ScheduledTask "EncryptSyncTEST" -Xml $EncryptSyncST.OuterXml -User $username -Password $password

I'm sure there must be a better way, but this is my current workaround.

I created a task with the triggers I wanted then grabbed the XML it generated.

Below I am creating the task, then pulling the XML for that new task, replacing my triggers, then un-registering the task it and re-registering it with the updated XML.

Long term, I will probably just use the full XML file for the task and replace the strings as needed, but this works for now.

#Credentials to run task as
$username = "$env:USERDOMAIN\$env:USERNAME" #current user
$password = "notmypass"

#Location of Scripts:
$psscript = "C:\test\test.ps1"
$Sourcedir ="C:\testsource\"
$destdir = "C:\testdest\"
$archivepassword = "notmypass"

####### Create New Scheduled Task
$action = New-ScheduledTaskAction -Execute "Powershell" -Argument "-WindowStyle Hidden '$EncryptSync' '$sourcedir' '$destdir' '$archivepassword'"
$trigger = New-ScheduledTaskTrigger -Once -At 7am -RepetitionDuration  (New-TimeSpan -Days 1)  -RepetitionInterval  (New-TimeSpan -Minutes 30)
$settings = New-ScheduledTaskSettingsSet -Hidden -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RunOnlyIfNetworkAvailable
$ST = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings
Register-ScheduledTask "EncryptSyncTEST" -InputObject $ST -User $username -Password $password


[xml]$EncryptSyncST = Export-ScheduledTask "EncryptSyncTEST"
$UpdatedXML = [xml]'<CalendarTrigger xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><Repetition><Interval>PT30M</Interval><Duration>P1D</Duration><StopAtDurationEnd>false</StopAtDurationEnd></Repetition><StartBoundary>2013-11-18T07:07:15</StartBoundary><Enabled>true</Enabled><ScheduleByDay><DaysInterval>1</DaysInterval></ScheduleByDay></CalendarTrigger>'
$EncryptSyncST.Task.Triggers.InnerXml = $UpdatedXML.InnerXML

Unregister-ScheduledTask "EncryptSyncTEST" -Confirm:$false
Register-ScheduledTask "EncryptSyncTEST" -Xml $EncryptSyncST.OuterXml -User $username -Password $password
那伤。 2025-01-30 03:21:33

我发现这是最简单的方法是使用schtasks.exe。请参阅 https:/httpps:/ /sdn.microsoft.com/en-us/library/windows/desktop/bb736357%28v = vs.85%299.aspx

schtasks.exe /CREATE /SC DAILY /MO 1 /TN 'task name' /TR 'powershell.exe C:\test.ps1' /ST 07:00 /RI 30 /DU 24:00

这会创建一个每天运行的任务,每30分钟重复每30分钟,每30分钟。天。

The easiest method I found to accomplish this is to use schtasks.exe. See full documentation at https://msdn.microsoft.com/en-us/library/windows/desktop/bb736357%28v=vs.85%29.aspx

schtasks.exe /CREATE /SC DAILY /MO 1 /TN 'task name' /TR 'powershell.exe C:\test.ps1' /ST 07:00 /RI 30 /DU 24:00

This creates a task that runs daily, repeats every 30 minutes, for a duration of 1 day.

用心笑 2025-01-30 03:21:33

https://stackoverflow.com/a/a/54674840/9673214
进行了轻微的修改,

@Steinip解决方案对我有用,并在“创建辅助触发”零件“添加”参数中

其值与“创建基本触发器”部分相同的值。创建基本触发器

$t1 = New-ScheduledTaskTrigger -Daily -At 01:00

创建辅助触发器:

$t2 = New-ScheduledTaskTrigger -Once -RepetitionInterval (New-TimeSpan -Minutes 15) -RepetitionDuration (New-TimeSpan -Hours 23 -Minutes 55) -At 01:00

做魔术:

$t1.Repetition = $t2.Repetition

New-ScheduledTask -Trigger $t1 -Action ...

https://stackoverflow.com/a/54674840/9673214
@SteinIP solution worked for me with slight modification

In 'create secondary trigger' part added '-At' parameter with same value as in 'create base trigger' part.

Create base trigger

$t1 = New-ScheduledTaskTrigger -Daily -At 01:00

Create secondary trigger:

$t2 = New-ScheduledTaskTrigger -Once -RepetitionInterval (New-TimeSpan -Minutes 15) -RepetitionDuration (New-TimeSpan -Hours 23 -Minutes 55) -At 01:00

Do the magic:

$t1.Repetition = $t2.Repetition

New-ScheduledTask -Trigger $t1 -Action ...
源来凯始玺欢你 2025-01-30 03:21:33

另一种方法是创建类似的多个触发器:

$startTimes     = @("12:30am","6am","9am","12pm","3pm","6pm")
$triggers = @()
foreach ( $startTime in $startTimes )
{
    $trigger = New-ScheduledTaskTrigger -Daily -At $startTime -RandomDelay (New-TimeSpan -Minutes $jitter)
    $triggers += $trigger
}

Another way to do it is just to create multiple triggers like so:

$startTimes     = @("12:30am","6am","9am","12pm","3pm","6pm")
$triggers = @()
foreach ( $startTime in $startTimes )
{
    $trigger = New-ScheduledTaskTrigger -Daily -At $startTime -RandomDelay (New-TimeSpan -Minutes $jitter)
    $triggers += $trigger
}
千紇 2025-01-30 03:21:33

如果您想在Windows 10上使用Infinate任务持续时间

$action = New-ScheduledTaskAction -Execute (Resolve-Path '.\main.exe')
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Hours 1)

Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "GettingDataFromDB" -Description "Dump of new data every hour"

If you wanna a infinate Task duration on Windows 10 just use this (Do not specify -RepetitionDuration)

$action = New-ScheduledTaskAction -Execute (Resolve-Path '.\main.exe')
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Hours 1)

Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "GettingDataFromDB" -Description "Dump of new data every hour"
空袭的梦i 2025-01-30 03:21:33

这是另一个对这个旧栗子似乎很好的变化,但不如其他解决方案复杂。它已在Server 2012 R2,Server 2016和Server 2019上进行了测试,每个OS上的默认PS版本。 “合并”触发器在2012年对我不起作用。

步骤很简单:

  1. 使用基本时间表创建计划的任务首先从新
  2. 任务中提取详细信息
  3. 修改触发器重复/持续时间
  4. 使用修改后的版本更新现有任务

。我将其设置为23小时,以使日期/时间语法更清晰一些)。持续时间和间隔使用相同的时间板格式。

# create the basic task trigger and scheduled task
$trigger = New-ScheduledTaskTrigger -Daily -At 15:55
$Settings = New-ScheduledTaskSettingsSet –StartWhenAvailable
Register-ScheduledTask -TaskName $TaskName -Trigger $Trigger -Action $Action -Setting $Settings -User $User

# Get the registered task parameters
$task = Get-Scheduledtask $TaskName

# Update the trigger parameters to the repetition intervals
$task.Triggers[0].Repetition.Duration = "P0DT23H0M0S"
$task.Triggers[0].Repetition.Interval = "P0DT1H0M0S"

# Commit the changes to the existing task
Set-ScheduledTask $task

请注意,如果您的任务具有多个触发因素 - 尽管如果您有重复间隔,那将是不寻常的 - 您需要修改任何触发器需要重复。该示例只有一个触发器,因此我们只选择触发器列表的第一个(也是唯一)成员 - $ task.triggers.triggers [0]

TIMESPAN是ISO 8601格式 - 它是带有带有的字符串没有空间。所需的数字值在时间指定之前(例如1H一小时,而不是H1)。该字符串必须包含列出的所有时间名称,并用0代替任何空值。 p(“周期”)开始表明它是持续时间而不是时间戳。

P(eriod)0D(ays)T(ime)0H(ours)0M(inutes)0S(econds)
P0DT1H0M0S  = 0 days, 1 hours, 0 minutes, 0 seconds
P0DT0H15M30S = 0 days, 0 hours, 15 minutes, 30 seconds

如果要更改任务的开始时间,则可以使用类似的方法修改触发器。这适用于-ONCE-daily任务。

$task = Get-ScheduledTask $taskname
$d = ([DateTime]::now).tostring("s")  # 2021-11-30T17:39:31
$task.Triggers[0].StartBoundary = $d
Set-ScheduledTask $task

Here's another variation that seems to work well for this old chestnut, but is less complex than some of the other solutions. It has been tested on Server 2012 R2, Server 2016 and Server 2019, with the default PS version on each OS. "Merging" the triggers didn't work for me on 2012. Didn't bother with the others.

The steps are simple:

  1. Create the scheduled task with the basic schedule first
  2. Extract the details from the new task
  3. Modify the trigger repetition/duration
  4. Update the existing task with the modified version

The example consists of a daily task that repeats every hour for a day (I've set it to 23 hours to make the date/time syntax a little clearer). The same timespan format is used for Duration and Interval.

# create the basic task trigger and scheduled task
$trigger = New-ScheduledTaskTrigger -Daily -At 15:55
$Settings = New-ScheduledTaskSettingsSet –StartWhenAvailable
Register-ScheduledTask -TaskName $TaskName -Trigger $Trigger -Action $Action -Setting $Settings -User $User

# Get the registered task parameters
$task = Get-Scheduledtask $TaskName

# Update the trigger parameters to the repetition intervals
$task.Triggers[0].Repetition.Duration = "P0DT23H0M0S"
$task.Triggers[0].Repetition.Interval = "P0DT1H0M0S"

# Commit the changes to the existing task
Set-ScheduledTask $task

Note that if your task has multiple triggers - although that'd be unusual if you have a repetition interval - you need to modify whichever trigger needs the repetitions. The example only has a single trigger, so we just select the first (and only) member of the list of triggers - $task.Triggers[0]

The timespan is ISO 8601 format - it's a string with no spaces. The required numeric value precedes the time designation (e.g. 1H for one hour, not H1). The string must contain all the time designations as listed, with a 0 substituting for any empty values. The P ("period") at the beginning indicates it's a duration rather than a timestamp.

P(eriod)0D(ays)T(ime)0H(ours)0M(inutes)0S(econds)
P0DT1H0M0S  = 0 days, 1 hours, 0 minutes, 0 seconds
P0DT0H15M30S = 0 days, 0 hours, 15 minutes, 30 seconds

You can use a similar method to modify the trigger if you want to change a start time on a task. This applies to -Once or -Daily tasks.

$task = Get-ScheduledTask $taskname
$d = ([DateTime]::now).tostring("s")  # 2021-11-30T17:39:31
$task.Triggers[0].StartBoundary = $d
Set-ScheduledTask $task
七堇年 2025-01-30 03:21:33

因为这似乎是收集所有黑客和解决方法的问题,所以让我也以2美分的价格投入:也可以使用任务调度程序的 com接口使用PowerShell不提供的选项更改计划的任务:

$taskName = "Clean-LogFiles"
$backupScriptPath = "$traceDir\Clean-LogFiles.ps1"

# Create a Task Scheduler task that runs every workday from 07:05 to 18:05, every hour. We can't specify the repetition pattern at this point yet, however.
$act = New-ScheduledTaskAction -Execute 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' -Argument "-File ""$backupScriptPath"""
$trig = New-ScheduledTaskTrigger -Daily -At "07:05"
$prin = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest
$sett = New-ScheduledTaskSettingsSet -StartWhenAvailable
$task = New-ScheduledTask -Action $act -Principal $prin -Trigger $trig -Settings $sett

#If it already exists, update it
$exists = (@(Get-ScheduledTask $taskName -ErrorAction SilentlyContinue).Count -ne 0)
if(!$exists) {
    Write-Verbose "Creating new scheduled task ""$taskName""..." -Verbose
    [void](Register-ScheduledTask $taskName -InputObject $task)
} 
else {
    Write-Verbose "Scheduled task ""$taskName"" already exists, updating it..." -Verbose
    [void](Set-ScheduledTask -TaskName $taskName -Action $act -Principal $prin -Trigger $trig -Settings $sett)
}

# Next, use the COM service to add the repetition pattern.
$service = New-Object -comobject Schedule.Service
$service.Connect()

$comFolder = $service.GetFolder("\")
$comTask = $comFolder.GetTask($taskName)
$comTaskDef = $comTask.Definition
$comTaskDef.Triggers[1].Repetition.Interval = "PT1H"
$comTaskDef.Triggers[1].Repetition.Duration = "PT11H"
$comTaskDef.Triggers[1].Repetition.StopAtDurationEnd = $true

# Now RegisterTaskDefinition() with TASK_UPDATE for it to become effective.
# See https://learn.microsoft.com/en-us/windows/win32/taskschd/taskfolder-registertaskdefinition
$updated = $comFolder.RegisterTaskDefinition(
    "$taskName",   # path
    $comTaskDef,   # definition
    4,             # flags, 4 = TASK_UPDATE
    $null,         # userId
    $null,         # password
    $null,         # logonType
    $null)         # ssdl

而不是使用Triggers Collection(即代码>触发器[1] ),您还可以直接更改$ comtaskDef.xmlText的内容。

As this seems to be the question in which all hacks and workarounds are collected, let me throw in my 2 cents as well: It's also possible to use the Task Scheduler's COM interfaces to change a scheduled task with the options that Powershell doesn't provide:

$taskName = "Clean-LogFiles"
$backupScriptPath = "$traceDir\Clean-LogFiles.ps1"

# Create a Task Scheduler task that runs every workday from 07:05 to 18:05, every hour. We can't specify the repetition pattern at this point yet, however.
$act = New-ScheduledTaskAction -Execute 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' -Argument "-File ""$backupScriptPath"""
$trig = New-ScheduledTaskTrigger -Daily -At "07:05"
$prin = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest
$sett = New-ScheduledTaskSettingsSet -StartWhenAvailable
$task = New-ScheduledTask -Action $act -Principal $prin -Trigger $trig -Settings $sett

#If it already exists, update it
$exists = (@(Get-ScheduledTask $taskName -ErrorAction SilentlyContinue).Count -ne 0)
if(!$exists) {
    Write-Verbose "Creating new scheduled task ""$taskName""..." -Verbose
    [void](Register-ScheduledTask $taskName -InputObject $task)
} 
else {
    Write-Verbose "Scheduled task ""$taskName"" already exists, updating it..." -Verbose
    [void](Set-ScheduledTask -TaskName $taskName -Action $act -Principal $prin -Trigger $trig -Settings $sett)
}

# Next, use the COM service to add the repetition pattern.
$service = New-Object -comobject Schedule.Service
$service.Connect()

$comFolder = $service.GetFolder("\")
$comTask = $comFolder.GetTask($taskName)
$comTaskDef = $comTask.Definition
$comTaskDef.Triggers[1].Repetition.Interval = "PT1H"
$comTaskDef.Triggers[1].Repetition.Duration = "PT11H"
$comTaskDef.Triggers[1].Repetition.StopAtDurationEnd = $true

# Now RegisterTaskDefinition() with TASK_UPDATE for it to become effective.
# See https://learn.microsoft.com/en-us/windows/win32/taskschd/taskfolder-registertaskdefinition
$updated = $comFolder.RegisterTaskDefinition(
    "$taskName",   # path
    $comTaskDef,   # definition
    4,             # flags, 4 = TASK_UPDATE
    $null,         # userId
    $null,         # password
    $null,         # logonType
    $null)         # ssdl

And instead of working with the triggers collection (i.e. Triggers[1]), you can also change the contents of the $comTaskDef.XmlText directly.

萤火眠眠 2025-01-30 03:21:33

旧问题,我不确定PowerShell CMDLET是否是必需的。但是我只是使用schtask。

如果您想每15分钟运行一次:

schtasks /f /create /tn taskname `
    /tr "powershell c:\job.ps1" /ru system `
    /sc minute /mo 15 /sd 01/01/2001 /st 00:00

这将在2001年1月1日午夜“触发”,每15分钟运行一次。因此,如果您今天创建它,它将仅在下一个事件间隔上运行。

如果您希望它每天都“触发”,则可以这样做:

schtasks /f /create /tn taskname `
    /tr "powershell c:\job.ps1" /ru system `
    /sc daily /sd 01/01/2001 /st 10:00 /du 12:14 /ri 15

这将在2001年1月1日上午10点“触发”,每15分钟每15分钟持续12小时14分钟。因此,如果您从今天开始,它将仅在下一个事件间隔上运行。

通常,我像顶部的“每15分钟”和“每天为X Times”这样的“每15分钟”运行。因此,如果我需要在上午10点和下午2点进行某些内容,我只需在第二个一号到5个小时将 /du更改为4个。然后,它每4小时重复一次,但只需5个小时。从技术上讲,您也许可以将其放在4:01的时间内,但我通常会给它一个小时以安全。

我曾经使用task.xml方法,并且在第二种情况下经历了非常艰难的时光,直到我在Task.xml中注意到它的导出。

<Triggers>
    <CalendarTrigger>
      <Repetition>
        <Interval>PT3H</Interval>
        <Duration>PT15H</Duration>
        <StopAtDurationEnd>false</StopAtDurationEnd>
      </Repetition>
      <StartBoundary>2017-11-27T05:45:00</StartBoundary>
      <ExecutionTimeLimit>PT10M</ExecutionTimeLimit>
      <Enabled>true</Enabled>
      <ScheduleByDay>
        <DaysInterval>1</DaysInterval>
      </ScheduleByDay>
    </CalendarTrigger>
  </Triggers>

这是一项工作,在5:45至7:45之间每3小时跑步一次。因此,我刚刚将间隔和持续时间喂入了每日时间表命令,并且效果很好。我只是使用旧日期进行标准化。我猜您今天总是可以启动它,然后它也可以。

要在远程服务器上运行此操作,我使用这样的东西:

$sb = { param($p); schtasks /f /create /tn `"$p`" /tr `"powershell c:\jobs\$p\job.ps1`" /ru system /sc daily /sd 01/01/2001 /st 06:00 /du 10:00 /ri (8*60) } }
Invoke-Command -ComputerName "server1" -ScriptBlock $sb -ArgumentList "job1"

Old question and I'm not sure if the powershell cmdlets are a requirement. But I just use schtasks.

If you want to run every 15 minutes:

schtasks /f /create /tn taskname `
    /tr "powershell c:\job.ps1" /ru system `
    /sc minute /mo 15 /sd 01/01/2001 /st 00:00

This will 'trigger' on 1/1/2001 midnight and run every 15 minutes. so if you create it today, it'll just run on the next event interval.

If you want it to 'trigger' every single day, you can do this:

schtasks /f /create /tn taskname `
    /tr "powershell c:\job.ps1" /ru system `
    /sc daily /sd 01/01/2001 /st 10:00 /du 12:14 /ri 15

This will 'trigger' on 1/1/2001 10am, and run every 15 minutes for 12 hours and 14 minutes. so if you start it today, it'll just run on the next event interval.

I normally run my 'every 15 minutes' like the top one and my 'every day for x times' like the bottom. So if i need to run something at say 10am and 2pm, i just change the /du on the second one to 5 hours and the /ri to 4. then it repeates every 4 hours, but only for 5 hours. Technically you may be able to put it at 4:01 for duration, but i generally give it an hour to be safe.

I used to use the task.xml method and was having a really tough time with the second scenario until I noticed in a task.xml that was exported it basically just has something like this below.

<Triggers>
    <CalendarTrigger>
      <Repetition>
        <Interval>PT3H</Interval>
        <Duration>PT15H</Duration>
        <StopAtDurationEnd>false</StopAtDurationEnd>
      </Repetition>
      <StartBoundary>2017-11-27T05:45:00</StartBoundary>
      <ExecutionTimeLimit>PT10M</ExecutionTimeLimit>
      <Enabled>true</Enabled>
      <ScheduleByDay>
        <DaysInterval>1</DaysInterval>
      </ScheduleByDay>
    </CalendarTrigger>
  </Triggers>

This was for a job that ran every 3 hours between 5:45 and 7:45. So I just fed the interval and duration into a daily schedule command and it worked fine. I just use an old date for standardization. I'm guessing you could always start it today and then it would work the same.

To run this on remote servers I use something like this:

$sb = { param($p); schtasks /f /create /tn `"$p`" /tr `"powershell c:\jobs\$p\job.ps1`" /ru system /sc daily /sd 01/01/2001 /st 06:00 /du 10:00 /ri (8*60) } }
Invoke-Command -ComputerName "server1" -ScriptBlock $sb -ArgumentList "job1"
永言不败 2025-01-30 03:21:33

在Windows 10中工作

Set-ExecutionPolicy RemoteSigned

$action=New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '‪C:\Users\hp\Anaconda3\python.exe ‪C:\Users\hp\Desktop\py.py'
$trigger = New-ScheduledTaskTrigger `
    -Once `
    -At (Get-Date) `
    -RepetitionInterval (New-TimeSpan -Minutes 15) `
    -RepetitionDuration (New-TimeSpan -Days (365 * 20))
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "ts2" -Description "tsspeech2" 

Working in Windows 10

Set-ExecutionPolicy RemoteSigned

$action=New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '‪C:\Users\hp\Anaconda3\python.exe ‪C:\Users\hp\Desktop\py.py'
$trigger = New-ScheduledTaskTrigger `
    -Once `
    -At (Get-Date) `
    -RepetitionInterval (New-TimeSpan -Minutes 15) `
    -RepetitionDuration (New-TimeSpan -Days (365 * 20))
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "ts2" -Description "tsspeech2" 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文