简体   繁体   中英

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

What I'm trying to accomplish: Create a scheduled task to run every 10 minutes. If the server restarts, continue the schedule.

I got it working with 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  

But most of our servers don't have v4 of powershell, so how can I do this with v3 and older? I found some code but can't seem to figure out the options on how to get this just right. This seems to create a task that runs only once. How can I make it run repetitively?

#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 

I have not tested this, but that code seems to be missing 'repetition' property mentioned here : http://msdn.microsoft.com/en-us/library/windows/desktop/aa446882(v=vs.85).aspx

Also note that, if you define the endboundary, then task will not run after the boundary. That code seems to be setting it to 5mins after registering it.

Nothing wrong with using .net object if you know what you are doing, and especially if schtasks cannot get the job done, but that does not seem to be the case here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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