Reputation: 75080
I have a powershell script which triggers an email and I have saved this as EmailScript.PS1
(no issues with the script,it runs just fine). I am planning to schedule this script whenever an event is logged in ,example:
Event ID:111 Description:Task terminated
I am successfully able to schedule this script whenever the required event is triggered.
However, currently it takes into account all the tasks (not my target task named xyz
for example) which is running in task scheduler.
I would like to schedule this event based task only when an event is triggered for a specific task(not all the tasks), but couldnot find such a filter/dropdown in the task scheduler create task tab.
Any suggestions/help would be highly appreciated.
Upvotes: 6
Views: 22307
Reputation: 306
I'd recommend using the custom XML event filter to do this, as it gives you a bit more flexibility to select what kind of events to trigger on.
To do this, do the following:
Note: Make sure to replace the TASK_NAME_HERE with the name of the task you want to trigger on. Additionally, you can replace TaskSuccessEvent with a different event name if you want to trigger on a different event type.
<QueryList>
<Query Id="0" Path="Microsoft-Windows-TaskScheduler/Operational">
<Select Path="Microsoft-Windows-TaskScheduler/Operational">*[EventData[@Name='TaskSuccessEvent'][Data[@Name='TaskName']='\TASK_NAME_HERE']]</Select>
</Query>
</QueryList>
Edit: To match multiple event IDs of a specific task, you can do the following:
<QueryList>
<Query Id="0" Path="Microsoft-Windows-TaskScheduler/Operational">
<Select Path="Microsoft-Windows-TaskScheduler/Operational">
*[EventData[Data[@Name='TaskName']='\TASK_NAME_HERE']]
and
*[System[(EventID='102' or EventID='103')]]
</Select>
</Query>
</QueryList>
For additional reading, see the following: https://blogs.technet.microsoft.com/askds/2011/09/26/advanced-xml-filtering-in-the-windows-event-viewer/
Upvotes: 8
Reputation: 174465
You could query the event log for the latest instance of the 111
event id and grab the task name from there:
$event = Get-WinEvent -FilterHashtable @{Id=111;LogName='Microsoft-Windows-TaskScheduler/Operational'} -MaxEvents 1
$taskName = $event.Properties[0].Value
if($taskName -ne '\xyz'){
# not the right task, abort
exit
}
Upvotes: 2