简体   繁体   中英

How to get trigger details associated with a task in task scheduler from powershell

So, basically i need to get the trigger details associated with a task which is created in task scheduler. 在此处输入图片说明

So, basically I want these information which i am going to be set in this trigger window such as its daily or weekly and repeat task duration as well as for a duration of etc.

Right now am able to get following information.

Name            : LastTaskResult
Value           : 0
CimType         : UInt32
Flags           : Property, ReadOnly, NotModified
IsValueModified : False

Name            : NextRunTime
Value           : 23-09-2015 11:26:56
CimType         : DateTime
Flags           : Property, ReadOnly, NotModified
IsValueModified : False

Name            : NumberOfMissedRuns
Value           : 0
CimType         : UInt32
Flags           : Property, ReadOnly, NotModified
IsValueModified : False

Name            : TaskName
Value           : test_Task
CimType         : String
Flags           : Property, Key, NotModified
IsValueModified : False

Name            : TaskPath
Value           : 
CimType         : String
Flags           : Property, Key, NotModified, NullValue
IsValueModified : False

So, basically my requirement is i have two servers. One is primary and other one is backup. I have scheduled the tasks in primary servers and periodically mirroring(robocopy) these tasks to backup server which works absolutely fine.

But when i change the trigger details or arguments in action tab it does not appear in backup server as i am just checking the task name is already present or not in backup server, if not am creating those tasks.

So is there any way to check the details regarding trigger(Daily or weekly etc, repetition details) or action(script and argument details) so that i can update the tasks accordingly in my seconadary server.

Is something like this what you are after:

$task = Get-ScheduledTask -TaskName "Adobe Flash Player Updater"
$taskTrigger = $task.Triggers[0]

$taskTrigger

It should give you an output similar to:

Enabled            : True
EndBoundary        : 
ExecutionTimeLimit : 
Id                 : 
Repetition         : MSFT_TaskRepetitionPattern
StartBoundary      : 2000-01-01T09:58:00+09:30
DaysInterval       : 1
RandomDelay        : 
PSComputerName     : 

Edit: Another way of doing this, using a ComObject connection instead

You could do it something like this:

$taskService = New-Object -ComObject "Schedule.Service"
$taskService.Connect($env:COMPUTERNAME)

$rootTaskFolder = $taskService.GetFolder("\")
$task = $rootTaskFolder.GetTask("Adobe Flash Player Updater")
$task

This will return the definition of the task. You could then use Compare-Object to see if it's the same on the backup server, and if not, export/import the task.

If you wanted to parse the XML you could do something like:

$parsedXML = [xml]$task.xml

You can then compare triggers by doings something like:

Compare-Object -DifferenceObject $remoteServerParsedXML.GetElementsByTagName("Triggers") -ReferenceObject $parsedXML.GetElementsByTagName("Triggers")

Does this get closer to what you are trying to achieve?

I think what you need is "basically" ;) an export/import function of your tasks.
Here is a sample code :

#connect to scheduler of you master server
$sch = New-Object -ComObject("Schedule.Service")
$sch.connect("$computername")

$root=$sch.GetFolder("\") 
$folder =$sch.GetFolder("\subfolder") #if you tasks are defined in a subfolder

#Export all tasks in the subfoder to $path folder in xml format
$folder.getTasks(0) | % {
    $path="c:\temp\tasks\$($_.name).xml" 
    New-Item -ItemType file -Path $path
    Set-Content -Path $path -Value $_.xml
}


#connect to scheduler of you backup server
$sch.connect("$backupcomputername")
$folder =$sch.GetFolder("\subfolder")

#import .xml from $task_path
$cred=get-credential # will ask for the credential of the user who run the tasks
Get-childItem -path $task_path -Filter *.xml | %{
    $task_name = $_.Name.Replace('.xml', '')
    $task_xml = Get-Content $_.FullName
    $task = $sch.NewTask($null)
    $task.XmlText = $task_xml
    $folder.RegisterTaskDefinition($task_name, $task, 6, $cred.UserName, $cred.GetNetworkCredential().password, 1, $null)
}

You'll probably think this is ugly, but it gets you all the pertinent info on the screen. Or you can keep it as an object you can manipulate or format from there...

$ScheduledTasks = get-scheduledtask | ? {$_.TaskPath -like '*Cool*'}

foreach ($item in $ScheduledTasks) {

    [string]$Name       = ($item.TaskName)
    [string]$Action     = ($item.Actions | select -ExpandProperty Execute)
    [datetime]$Start    = ($item.Triggers | select -ExpandProperty StartBoundary)
    [string]$Repetition = ($item.Triggers.Repetition | select -ExpandProperty interval)
    [string]$Duration   = ($item.triggers.Repetition | select -ExpandProperty duration)

    $splat = @{

    'Name'       = $Name
    'Action'     = $Action
    'Start'      = $start
    'Repetition' = $Repetition
    'Duration'   = $Duration

    }

    $obj = New-Object -TypeName PSObject -property $splat

    $obj | Write-Output
}

It will get you something like this:

Repetition : PT1H
Duration   : P1D
Name       : MyCoolTask
Action     : C:\MyPath\MyCoolTask\MyCoolTask.exe
Start      : 1/10/2014 3:00:00 AM

The repetition is every hour (hence the 1H in the PT1H) The Duration is the max run time (1 day) The Name is obviously the name of your task, action and start time should also be self explanatory.

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