繁体   English   中英

如何在PowerShell v3中使用ComObject Schedule.service创建计划任务?

[英]How can I create a scheduled task with ComObject Schedule.service in PowerShell v3?

我要完成的任务:创建一个计划任务,每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  

但是我们的大多数服务器没有v4的powershell,那么我该如何在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 

我尚未对此进行测试,但是该代码似乎缺少此处提到的“重复”属性: http : //msdn.microsoft.com/zh-cn/library/windows/desktop/aa446882(v=vs.85).aspx

另请注意,如果定义了边界,则任务将不会在边界之后运行。 该代码似乎在注册后将其设置为5分钟。

如果您知道自己在做什么,尤其是在schtasks无法完成工作的情况下,使用.net对象没什么大不了的,但在这里似乎并非如此。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM