我想要完成的事情: 创建一个每10分钟运行一次的计划任务。 如果服务器重新启动,请继续执行计划。
我使用PowerShell v4:
$account = $cred.Username
$password = $cred.GetNetworkCredential().password
$taskname = 'GCCOPS Asset Agent'
$description = "gccops agent"
$action = New-ScheduledTaskAction -Execute "Powershell" -Argument '-file "C:\GCCAgent\Agent.ps1"'
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval (New-TimeSpan -Minutes 10) -RepetitionDuration (New-TimeSpan -Days 9999)
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Minutes 5)
$Result = Register-ScheduledTask -TaskName $taskName -Trigger $trigger -Action $action -Setting $settings -description $description -User $account -RunLevel 1 -Password $password -Force
但是我们的大多数服务器都没有PowerShell的v4,那么我怎么能用v3和更早版本呢? 我找到了一些代码,但似乎无法弄清楚如何才能做到这一点。这似乎创建了一个只运行一次的任务。我怎样才能让它重复运行?
#create task
function xmltime ([datetime] $d){ $d.Touniversaltime().tostring("u") -replace " ","T"}
[string]$delay = '1'
[string]$delay2 = '5'
$ts = New-Object -ComObject Schedule.service
$ts.connect()
$nt = $ts.newtask(0)
$ri = $nt.registrationinfo
$ri.description = $taskname
$ri.author = "$env:username"
$prince = $nt.principal
$prince.logontype = 6
$trigger = $nt.triggers.create(1)
$trigger.startboundary = xmltime ((get-date).addminutes($delay))
$trigger.Endboundary = xmltime ((Get-date).addminutes($delay2))
$trigger.ExecutionTimelimit = "PT5M"
$trigger.enabled = $true
$trigger.id = "Trigger $taskname"
$action = $nt.actions.create(0)
$action.path = @(Get-Command powershell.exe)[0].Definition
$action.arguments = C:\GCCAgent\Agent.ps1"
$tsfolder = $ts.getfolder("\")
$tsfolder.RegisterTaskDefinition("$taskname", $nt, 6,$account, $password, 6) | out-null
答案 0 :(得分:1)
我没有对此进行测试,但该代码似乎缺失了重复'这里提到的财产:http://msdn.microsoft.com/en-us/library/windows/desktop/aa446882(v=vs.85).aspx
另请注意,如果您定义了endboundary,那么任务将不会在边界之后运行。该代码似乎在注册后将其设置为5分钟。
如果您知道自己在做什么,使用.net对象没有错,特别是如果schtasks无法完成工作,但这似乎并非如此。