0

I've looked at this question where it's shown how to create a trigger to run after a service is started, but I'm struggling to figure out how to do this via Powershell.

New-ScheduledTaskTrigger seems to only support time-based triggers, but not based on an event, like a service starting. Any pointers?

1 Answer 1

1

New-ScheduledTaskTrigger unfortunately does not have a way to create event driven triggers. The PS community has requested that this be implemented.

We should be able to combine the XML you're working with with code that creates tasks using .NET. Just replace the user, pass, and service name.

$taskRunAsuser = "domain\user"
$taskRunAsUserPwd = "password"
$Service = new-object -ComObject ("Schedule.Service")
$Service.Connect($env:computername)
$RootFolder = $Service.GetFolder("\")
$TaskDefinition = $Service.NewTask(0)
$settings = $taskDefinition.Settings
$settings.Enabled = $true
$settings.StartWhenAvailable = $true
$settings.Hidden = $false
$Triggers = $TaskDefinition.Triggers
$Trigger = $Triggers.Create(0)
#$Trigger.Id = '4800'
$Trigger.Subscription = "<QueryList> 
<Query Id='0'> 
   <Select Path='System'> 
      *[EventData[Data[@Name='param1'] and (Data='YOUR SERVICE NAME')]] 
      and
      *[EventData[Data[@Name='param2'] and (Data='running')]] 
    </Select> 
</Query> 
</QueryList>"
$Trigger.Enabled = $true
$Action = $TaskDefinition.Actions.Create(0)
$Action.Path = 'ping.exe'
$Action.Arguments = '8.8.8.8 > C:\ping.log'
$rootFolder.RegisterTaskDefinition('Test',$TaskDefinition,6,$taskRunAsUser,$taskRunAsUserPwd,1)
2
  • Amazing example, really appreciated! Commented Dec 18, 2017 at 10:13
  • Doesn't work for me, I got syntax and run-time error Commented Feb 5, 2018 at 16:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .