zexal985236
zexal985236

Reputation: 43

Use Powershell to add property "On Workstation Unlock" to scheduled task

I have a task with two triggers. The first one starts with logon of any user and runs every 3 minutes indefinitely. The second one starts when "on workstation UNlock". I want to also run this second trigger every 10 minutes and indefinitely after triggered. I have the following part that corresponds to "On Workstation Unlock", but how do I get everything together?

$Task = Get-ScheduledTask -TaskName "Task"
$Task.Triggers.Repetition.Duration = "" 
$Task.Triggers.Repetition.Interval = "PT10M"

    $stateChangeTrigger = Get-CimClass `
         -Namespace ROOT\Microsoft\Windows\TaskScheduler `
         -ClassName MSFT_TaskSessionStateChangeTrigger

    $onUnlockTrigger = New-CimInstance `
        -CimClass $stateChangeTrigger `
        -Property @{
        StateChange = 8  # TASK_SESSION_STATE_CHANGE_TYPE.TASK_SESSION_UNLOCK (taskschd.h)
    } `
       -ClientOnly

Upvotes: 1

Views: 3966

Answers (1)

Klaidonis
Klaidonis

Reputation: 639

You can do so in the following way (updating the task twice):

# Create the trigger class for $T2
$StateChangeTrigger = Get-CimClass `
    -Namespace Root/Microsoft/Windows/TaskScheduler `
    -ClassName MSFT_TaskSessionStateChangeTrigger

# Define triggers (the type)
$T1 = New-ScheduledTaskTrigger -AtLogOn
$T2 = New-CimInstance `
    -CimClass $StateChangeTrigger `
    -Property @{StateChange = 8} `
    -ClientOnly

# Update the task; Get its new settings
Set-ScheduledTask 'Task' -Trigger $T1,$T2
$Task = Get-ScheduledTask -TaskName 'Task'

# Set triggers options
$Task.Triggers[0].Repetition.Interval = 'PT3M'
$Task.Triggers[1].Repetition.Interval = 'PT10M'

# Final task update
$Task | Set-ScheduledTask

There is also a good example by @Jarrad here on how to modify triggers for your situation but using the COM approach.

# UPDATE

It is possible to do the above without modifying the task twice by creating the appropriate CIM instance for the repetition pattern:

# Create the trigger class for $T2
$StateChangeTrigger = Get-CimClass `
    -Namespace Root/Microsoft/Windows/TaskScheduler `
    -ClassName MSFT_TaskSessionStateChangeTrigger

# Create the repetition pattern class
$RepetitionPattern = Get-CimClass `
    -Namespace Root/Microsoft/Windows/TaskScheduler `
    -ClassName MSFT_TaskRepetitionPattern

# Define a new repetition pattern
$R = New-CimInstance `
    -CimClass $RepetitionPattern `
    -Property @{Interval = 'PT3M'} `
    -ClientOnly

# Define triggers
$T1 = New-ScheduledTaskTrigger -AtLogOn
$T1.Repetition = $R
$T2 = New-CimInstance `
    -CimClass $StateChangeTrigger `
    -Property @{StateChange = 8;
                Repetition = $R} `
    -ClientOnly
$T2.Repetition.Interval = 'PT10M'

# Update the task and done
Set-ScheduledTask 'Task' -Trigger $T1,$T2

The corresponding reference links:

Upvotes: 5

Related Questions