具有每日触发和重复间隔的计划任务

时间:2013-11-20 22:57:31

标签: powershell powershell-v3.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个标记。如果我在注册后再回来将任务更新到每天,它会擦除​​重复的触发器。

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

感谢任何帮助。

编辑:解决重复的问题。帖子“Powershell v3 New-JobTrigger daily with repetition”中的问题也是一样的。但正如我之前评论的那样,没有一个答案可以解决这个问题。标记的答案正是我已经拥有的,它设置了一个-Once触发器的任务,然后将其更新为每5分钟重复一天。在第一天之后,该任务将永远不会再次触发。它没有解决每天触发任务的问题,重复和持续时间直到下一次触发。

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

注意:我找到了一种解决方法,但不是很好。目前,使用powershell定义自定义触发器的最简单方法似乎是操纵Scheduled Task XML并使用Register-ScheduledTask直接导入

10 个答案:

答案 0 :(得分:17)

虽然计划任务触发器的PowerShell界面有限,但如果您将func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) { if(error != nil){ print(error) } self.lockInterfaceRotation = false let backgroundRecordId: UIBackgroundTaskIdentifier = self.backgroundRecordId self.backgroundRecordId = UIBackgroundTaskInvalid //create mutable composition of video and slow it down let videoAsset = AVURLAsset(URL: outputFileURL, options: nil) let mixComposition = AVMutableComposition() let videoTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID(kCMPersistentTrackID_Invalid)) let audioTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID(kCMPersistentTrackID_Invalid)) let sourceVideoTrack = videoAsset.tracksWithMediaType(AVMediaTypeVideo)[0] let sourceAudioTrack = videoAsset.tracksWithMediaType(AVMediaTypeAudio)[0] do{ try videoTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), ofTrack: sourceVideoTrack, atTime: kCMTimeZero) try audioTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), ofTrack: sourceAudioTrack, atTime: kCMTimeZero) }catch _ { print("ERROR could not insert time range") return } /* ** THE PART THAT ISN'T WORKING - When I add this section everything breaks ** //slow video down for slow mo effect let videoDuration = videoAsset.duration; let videoScaleFactor = 2 * videoDuration.value videoTrack.scaleTimeRange(CMTimeRangeMake(kCMTimeZero, videoDuration), toDuration: CMTimeMake(videoScaleFactor, videoDuration.timescale)) */ // Make mutable combination // -- Create instruction let instruction = AVMutableVideoCompositionInstruction() instruction.timeRange = CMTimeRangeMake(kCMTimeZero, videoAsset.duration) let videoLayerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack) instruction.layerInstructions = [videoLayerInstruction] let mutableComposition = AVMutableVideoComposition() mutableComposition.renderSize = videoTrack.naturalSize mutableComposition.frameDuration = CMTimeMake(1, 20) mutableComposition.instructions = [instruction] // -- Get path let fileName = "/editedVideo-\(arc4random() % 10000).mp4" let allPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let docsPath = allPaths[0] as NSString let exportPath = docsPath.stringByAppendingFormat(fileName) let exportUrl = NSURL.fileURLWithPath(exportPath as String) print("Tracks before export: \(mixComposition.tracks.count). File URL: \(exportUrl)") // -- Remove old video if exists if NSFileManager.defaultManager().fileExistsAtPath(exportPath as String) { print("Deleting existing file\n") do{ try NSFileManager.defaultManager().removeItemAtPath(exportPath as String) }catch _ { print("Error deleting old video file") } } // -- Create exporter let exporter = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality) exporter!.videoComposition = mutableComposition exporter!.outputFileType = AVFileTypeMPEG4 exporter!.outputURL = exportUrl exporter!.shouldOptimizeForNetworkUse = true // -- Export video exporter!.exportAsynchronouslyWithCompletionHandler({ self.exportDidFinish(exporter!) }) } func exportDidFinish(exporter: AVAssetExportSession) { // Save video to photo album let assetLibrary = ALAssetsLibrary() assetLibrary.writeVideoAtPathToSavedPhotosAlbum(exporter.outputURL, completionBlock: {(url: NSURL!, error: NSError!) in print("Saved video to album \(exporter.outputURL)") if (error != nil) { print("Error saving video") } }) // Check asset tracks print("SUCCESS exporting video") } 设置为RepetitionDuration,则会导致“无限期”持续时间。

[System.TimeSpan]::MaxValue

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

答案 1 :(得分:12)

以下是在Powershell(我的机器上的v5,YMMV)中创建计划任务的方法,该任务将在每天12 AM 每天开始,每小时重复 <他们当天剩下的时间。因此它会无限期地运行。我认为这是一个优秀的方法,而不是像前面评论的那样将-RepetitionDuration设置为([timespan]::MaxValue),因为触发器将在任务计划程序中显示为:

  

每天凌晨12:00 - 触发后,每30分钟重复一次,持续1天。

而不是将任务注册的日期作为使用-Once -At 12am的方法出现在触发器中,而是将触发器创建为简单的-Daily -At 12am,注册任务然后访问其他一些属性任务触发器属性;

$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.

答案 2 :(得分:9)

我确信必须有更好的方法,但这是我目前的解决方法。

我使用我想要的触发器创建了一个任务,然后抓取了它生成的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

答案 3 :(得分:4)

我发现实现此目的的最简单方法是使用schtasks.exe。请参阅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

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

答案 4 :(得分:3)

另一种方法是创建多个触发器,如下所示:

import 'rxjs/add/operator/let';
import 'rxjs/add/operator/take';
import { Component, ChangeDetectionStrategy } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';

import * as fromRoot from '../reducers';
import * as book from '../actions/book';
import { Book } from '../models/book';

@Component({
  selector: 'bc-find-book-page',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: '
    <bc-book-search [query]="searchQuery$ | async" [searching]="loading$ | async" (search)="search($event)"></bc-book-search>
    <bc-book-preview-list [books]="books$ | async"></bc-book-preview-list>
  '
})
export class FindBookPageComponent {
  searchQuery$: Observable<string>;
  books$: Observable<Book[]>;
  loading$: Observable<boolean>;

  constructor(private store: Store<fromRoot.State>) {
    this.searchQuery$ = store.select(fromRoot.getSearchQuery).take(1);
    this.books$ = store.select(fromRoot.getSearchResults);
    this.loading$ = store.select(fromRoot.getSearchLoading);
  }

  search(query: string) {
    this.store.dispatch(new book.SearchAction(query));
  }
}

答案 5 :(得分:1)

如果你想在Windows 10上使用infinate任务持续时间,请使用它(不要指定-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"

答案 6 :(得分:1)

创建基本触发器:

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

创建辅助触发器:

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

从辅助对象中获取重复对象,并将其插入基本触发器中:

$t1.Repetition = $t2.Repetition

鲍勃是你的叔叔

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

答案 7 :(得分:0)

https://stackoverflow.com/a/54674840/9673214 @SteinIP解决方案为我工作,但稍作修改

在“创建辅助触发器”部分中添加了“ -At”参数,其值与“创建基本触发器”部分中的值相同。

创建基本触发器

$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 ...

答案 8 :(得分:0)

在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" 

答案 9 :(得分:0)

老问题,我不确定是否需要 powershell cmdlet。但我只使用 schtasks。

如果您想每 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 分钟运行一次,持续 12 小时 14 分钟。因此,如果您今天启动它,它将在下一个事件间隔运行。

我通常像顶部一样运行“每 15 分钟”,而像底部一样运行“每天 x 次”。因此,如果我需要在上午 10 点和下午 2 点运行某些内容,我只需将第二个的 /du 更改为 5 小时,将 /ri 更改为 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"