Repository navigation
Expand file tree
/
Copy pathInvoke-SetExternalMonitorStateTaskWrapper.ps1
More file actions
584 lines (475 loc) · 20.2 KB
/
Copy pathInvoke-SetExternalMonitorStateTaskWrapper.ps1
File metadata and controls
584 lines (475 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
<#
.SYNOPSIS
Wraps Set-ExternalMonitorState.ps1 for Task Scheduler execution.
.DESCRIPTION
Runs Set-ExternalMonitorState.ps1 in a child PowerShell process so the wrapper
can schedule a detached helper to record the final Task Scheduler completion
history entry after the task action exits.
.EXAMPLE
.\Invoke-SetExternalMonitorStateTaskWrapper.ps1 -PowerAction On -InputSource HDMI1
Runs the monitor-state script and records Task Scheduler history details in the
shared log file when the wrapper is launched by Task Scheduler.
#>
[CmdletBinding(DefaultParameterSetName = 'Run')]
param(
[Parameter(ParameterSetName = 'Run')]
[string]$ScriptPath = 'C:\programs\PowerShell\Scripts\Local\Utility\Set-ExternalMonitorState.ps1',
[Parameter(ParameterSetName = 'Run')]
[string]$LogDirectory = 'C:\Windows\Logs\Set-ExternalMonitorState',
[Parameter(ParameterSetName = 'Run')]
[string]$LogFileName = 'Set-ExternalMonitorState.log',
[Parameter(ParameterSetName = 'Run', ValueFromRemainingArguments)]
[object[]]$ScriptArguments,
[Parameter(Mandatory, ParameterSetName = 'Finalize')]
[switch]$FinalizeTaskHistory,
[Parameter(Mandatory, ParameterSetName = 'Finalize')]
[string]$TaskName,
[Parameter(ParameterSetName = 'Finalize')]
[string]$TaskInstanceId,
[Parameter(Mandatory, ParameterSetName = 'Finalize')]
[string]$FinalizerLogPath
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$TaskSchedulerHistoryLogName = 'Microsoft-Windows-TaskScheduler/Operational'
$FallbackLogDirectory = Join-Path -Path ([Environment]::GetFolderPath('LocalApplicationData')) -ChildPath 'Set-ExternalMonitorState\Logs'
function Get-TaskSchedulerEventData {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[System.Diagnostics.Eventing.Reader.EventRecord]$EventRecord
)
$eventData = @{}
[xml]$eventXml = $EventRecord.ToXml()
foreach ($dataNode in @($eventXml.Event.EventData.Data)) {
$dataName = [string]$dataNode.Name
if ([string]::IsNullOrWhiteSpace($dataName)) {
continue
}
$eventData[$dataName] = [string]$dataNode.InnerText
}
return $eventData
}
function Initialize-Directory {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$Path
)
if (-not (Test-Path -LiteralPath $Path -PathType Container)) {
New-Item -Path $Path -ItemType Directory -Force | Out-Null
}
}
function Get-EffectiveLogPath {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$Directory,
[Parameter(Mandatory)]
[string]$FileName
)
try {
Initialize-Directory -Path $Directory
return (Join-Path -Path $Directory -ChildPath $FileName)
}
catch {
Initialize-Directory -Path $FallbackLogDirectory
return (Join-Path -Path $FallbackLogDirectory -ChildPath $FileName)
}
}
function Write-WrapperLog {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$LogPath,
[Parameter(Mandatory)]
[string]$Message,
[ValidateSet('INFO', 'WARN', 'ERROR')]
[string]$Level = 'INFO'
)
$timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
$entry = "[$timestamp] [$Level] [Wrapper] $Message"
Add-Content -Path $LogPath -Value $entry -ErrorAction Stop
}
function Get-ProcessAncestry {
[CmdletBinding()]
param()
$processChain = [System.Collections.Generic.List[object]]::new()
$visitedProcessIds = [System.Collections.Generic.HashSet[int]]::new()
$currentProcessId = [int]$PID
$allCimProcesses = @{}
foreach ($cimProc in @(Get-CimInstance -ClassName Win32_Process -ErrorAction SilentlyContinue)) {
$allCimProcesses[[int]$cimProc.ProcessId] = $cimProc
}
while ($currentProcessId -gt 0 -and $visitedProcessIds.Add($currentProcessId)) {
$processRecord = $allCimProcesses[$currentProcessId]
if ($null -eq $processRecord) {
break
}
try {
$processObject = Get-Process -Id $currentProcessId -ErrorAction Stop
}
catch {
break
}
[void]$processChain.Add([pscustomobject]@{
ProcessId = [int]$processRecord.ProcessId
ParentProcessId = [int]$processRecord.ParentProcessId
Name = [string]$processObject.ProcessName
CommandLine = [string]$processRecord.CommandLine
StartTime = [datetime]$processObject.StartTime
})
if ($processRecord.ParentProcessId -le 0 -or $processRecord.ParentProcessId -eq $processRecord.ProcessId) {
break
}
$currentProcessId = [int]$processRecord.ParentProcessId
}
return @($processChain)
}
function Get-ScheduledTaskContextForCurrentProcess {
[CmdletBinding()]
param()
$processAncestry = @(Get-ProcessAncestry)
if ($processAncestry.Count -eq 0) {
return $null
}
$processesById = @{}
foreach ($processInfo in $processAncestry) {
$processesById[[int]$processInfo.ProcessId] = $processInfo
}
$startWindow = (@($processAncestry | Select-Object -ExpandProperty StartTime | Sort-Object) | Select-Object -First 1).AddMinutes(-5)
try {
$launchEvents = @(
Get-WinEvent -FilterHashtable @{
LogName = $TaskSchedulerHistoryLogName
Id = 129
StartTime = $startWindow
} -ErrorAction Stop
)
}
catch {
return $null
}
$launchCandidates = @(
foreach ($launchEvent in $launchEvents) {
$eventData = Get-TaskSchedulerEventData -EventRecord $launchEvent
$processId = 0
if (-not [int]::TryParse([string]$eventData.ProcessID, [ref]$processId)) {
continue
}
if (-not $processesById.ContainsKey($processId)) {
continue
}
$processEntry = $processesById[$processId]
[pscustomobject]@{
Event = $launchEvent
EventData = $eventData
MatchedProcess = $processEntry
IsCurrentProcess = ($processEntry.ProcessId -eq $PID)
Delta = [math]::Abs(($launchEvent.TimeCreated - $processEntry.StartTime).TotalSeconds)
}
}
)
$selected = @(
$launchCandidates |
Sort-Object -Property @{ Expression = 'IsCurrentProcess'; Descending = $true }, @{ Expression = 'Delta'; Descending = $false }, @{ Expression = { $_.Event.TimeCreated }; Descending = $true }
) | Select-Object -First 1
if ($null -eq $selected) {
return $null
}
$taskHistory = @(
Get-WinEvent -FilterHashtable @{
LogName = $TaskSchedulerHistoryLogName
Id = 100, 200
StartTime = $selected.Event.TimeCreated.AddMinutes(-2)
} -ErrorAction SilentlyContinue
)
$taskName = [string]$selected.EventData.TaskName
$actionStartCandidates = [System.Collections.Generic.List[object]]::new()
$taskStartCandidates = [System.Collections.Generic.List[object]]::new()
foreach ($historyEvent in $taskHistory) {
$historyData = Get-TaskSchedulerEventData -EventRecord $historyEvent
if ([string]$historyData.TaskName -ne $taskName) {
continue
}
$entry = [pscustomobject]@{ Event = $historyEvent; EventData = $historyData }
if ($historyEvent.Id -eq 200 -and [string]$historyData.TaskInstanceId) {
[void]$actionStartCandidates.Add($entry)
}
if ($historyEvent.Id -eq 100) {
[void]$taskStartCandidates.Add($entry)
}
}
$actionStartEvent = @($actionStartCandidates | Sort-Object -Property @{ Expression = { $_.Event.TimeCreated }; Descending = $true }) | Select-Object -First 1
$taskStartEvent = @($taskStartCandidates | Sort-Object -Property @{ Expression = { $_.Event.TimeCreated }; Descending = $true }) | Select-Object -First 1
$resolvedTaskStartTime = if ($null -ne $taskStartEvent) {
[datetime]$taskStartEvent.Event.TimeCreated
}
else {
[datetime]$selected.Event.TimeCreated
}
$triggerClassification = Get-ScheduledTaskTriggerClassification -TaskName $taskName -TaskStartTime $resolvedTaskStartTime -TaskLaunchTime ([datetime]$selected.Event.TimeCreated)
return [pscustomobject]@{
TaskName = $taskName
TaskInstanceId = if ($null -ne $actionStartEvent) { [string]$actionStartEvent.EventData.TaskInstanceId } elseif ($null -ne $taskStartEvent) { [string]$taskStartEvent.EventData.InstanceId } else { $null }
TaskActionName = if ($null -ne $actionStartEvent) { [string]$actionStartEvent.EventData.ActionName } else { $null }
TaskStartTime = $resolvedTaskStartTime
TaskLaunchTime = [datetime]$selected.Event.TimeCreated
TaskTriggerSource = [string]$triggerClassification.TriggerSource
TaskTriggerReason = [string]$triggerClassification.Reason
}
}
function Get-ScheduledTaskDefinitionXml {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$TaskName
)
$taskPath = '\'
$shortTaskName = $TaskName.Trim()
$taskNameParts = [regex]::Match($shortTaskName, '^(?<TaskPath>.*\\)(?<ShortTaskName>[^\\]+)$')
if ($taskNameParts.Success) {
$taskPath = [string]$taskNameParts.Groups['TaskPath'].Value
$shortTaskName = [string]$taskNameParts.Groups['ShortTaskName'].Value
}
try {
$taskDefinition = Export-ScheduledTask -TaskPath $taskPath -TaskName $shortTaskName -ErrorAction Stop
if ([string]::IsNullOrWhiteSpace($taskDefinition)) {
return $null
}
return [xml]$taskDefinition
}
catch {
return $null
}
}
function Get-ScheduledTaskTriggerClassification {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$TaskName,
[datetime]$TaskStartTime,
[datetime]$TaskLaunchTime
)
$taskDefinitionXml = Get-ScheduledTaskDefinitionXml -TaskName $TaskName
$supportsLogonTrigger = $false
$supportsUnlockTrigger = $false
if ($null -ne $taskDefinitionXml) {
$namespaceManager = [System.Xml.XmlNamespaceManager]::new($taskDefinitionXml.NameTable)
[void]$namespaceManager.AddNamespace('task', 'http://schemas.microsoft.com/windows/2004/02/mit/task')
$supportsLogonTrigger = ($null -ne $taskDefinitionXml.SelectSingleNode('/task:Task/task:Triggers/task:LogonTrigger', $namespaceManager))
$supportsUnlockTrigger = ($null -ne $taskDefinitionXml.SelectSingleNode('/task:Task/task:Triggers/task:SessionStateChangeTrigger[task:StateChange = "SessionUnlock"]', $namespaceManager))
}
$referenceTime = if ($TaskStartTime -is [datetime]) {
$TaskStartTime
}
elseif ($TaskLaunchTime -is [datetime]) {
$TaskLaunchTime
}
else {
$null
}
$recentLogonEvent = $null
$logonDetectionWindow = [TimeSpan]::FromSeconds(60)
if ($supportsLogonTrigger -and $referenceTime -is [datetime]) {
try {
$recentLogonEvent = @(
Get-WinEvent -FilterHashtable @{
LogName = 'System'
ProviderName = 'Microsoft-Windows-Winlogon'
Id = 7001
StartTime = $referenceTime.Subtract($logonDetectionWindow)
EndTime = $referenceTime.AddSeconds(5)
} -ErrorAction Stop |
Where-Object { $_.Message -like 'User Log-on Notification*' } |
Sort-Object -Property TimeCreated -Descending
) | Select-Object -First 1
}
catch {
$recentLogonEvent = $null
}
}
if ($null -ne $recentLogonEvent) {
return [pscustomobject]@{
TriggerSource = 'Logon'
Reason = "Matched a Winlogon user logon notification at $($recentLogonEvent.TimeCreated.ToString('yyyy-MM-dd HH:mm:ss')) within $([int]$logonDetectionWindow.TotalSeconds) seconds of task start."
}
}
if ($supportsUnlockTrigger -and -not $supportsLogonTrigger) {
return [pscustomobject]@{
TriggerSource = 'Unlock'
Reason = 'Task definition exposes only a session unlock trigger.'
}
}
if ($supportsLogonTrigger -and -not $supportsUnlockTrigger) {
return [pscustomobject]@{
TriggerSource = 'Logon'
Reason = 'Task definition exposes only a logon trigger.'
}
}
if ($supportsUnlockTrigger -and $supportsLogonTrigger) {
return [pscustomobject]@{
TriggerSource = 'Unlock'
Reason = "Task definition includes both logon and unlock triggers, and no Winlogon user logon notification was found within $([int]$logonDetectionWindow.TotalSeconds) seconds of task start."
}
}
return [pscustomobject]@{
TriggerSource = 'Unknown'
Reason = 'Task trigger type could not be resolved from the task definition or available event history.'
}
}
function Get-ScheduledTaskCompletionEvent {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$TaskName,
[string]$TaskInstanceId,
[datetime]$StartTime = (Get-Date).AddMinutes(-10)
)
$historyEvents = @(
Get-WinEvent -FilterHashtable @{
LogName = $TaskSchedulerHistoryLogName
Id = 102, 201
StartTime = $StartTime
} -ErrorAction SilentlyContinue
)
$completionCandidates = @(
foreach ($historyEvent in $historyEvents) {
$historyData = Get-TaskSchedulerEventData -EventRecord $historyEvent
if ([string]$historyData.TaskName -ne $TaskName) {
continue
}
$sameInstance = $true
if (-not [string]::IsNullOrWhiteSpace($TaskInstanceId)) {
$sameInstance = (
([string]$historyData.TaskInstanceId -eq $TaskInstanceId) -or
([string]$historyData.InstanceId -eq $TaskInstanceId)
)
}
if (-not $sameInstance) {
continue
}
[pscustomobject]@{
Event = $historyEvent
EventData = $historyData
}
}
)
return @(
$completionCandidates |
Sort-Object -Property @{ Expression = { $_.Event.TimeCreated }; Descending = $true }
) | Select-Object -First 1
}
function Start-TaskHistoryFinalizer {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$TaskName,
[string]$TaskInstanceId,
[Parameter(Mandatory)]
[string]$LogPath
)
$hostPath = (Get-Process -Id $PID -ErrorAction Stop).Path
$startInfo = [System.Diagnostics.ProcessStartInfo]::new()
$startInfo.FileName = $hostPath
$startInfo.UseShellExecute = $false
$startInfo.CreateNoWindow = $true
[void]$startInfo.ArgumentList.Add('-NoProfile')
[void]$startInfo.ArgumentList.Add('-ExecutionPolicy')
[void]$startInfo.ArgumentList.Add('Bypass')
[void]$startInfo.ArgumentList.Add('-File')
[void]$startInfo.ArgumentList.Add($PSCommandPath)
[void]$startInfo.ArgumentList.Add('-FinalizeTaskHistory')
[void]$startInfo.ArgumentList.Add('-TaskName')
[void]$startInfo.ArgumentList.Add($TaskName)
if (-not [string]::IsNullOrWhiteSpace($TaskInstanceId)) {
[void]$startInfo.ArgumentList.Add('-TaskInstanceId')
[void]$startInfo.ArgumentList.Add($TaskInstanceId)
}
[void]$startInfo.ArgumentList.Add('-FinalizerLogPath')
[void]$startInfo.ArgumentList.Add($LogPath)
$process = [System.Diagnostics.Process]::new()
$process.StartInfo = $startInfo
[void]$process.Start()
}
if ($FinalizeTaskHistory) {
$deadline = (Get-Date).AddMinutes(2)
$completionEvent = $null
while ((Get-Date) -lt $deadline) {
$completionEvent = Get-ScheduledTaskCompletionEvent -TaskName $TaskName -TaskInstanceId $TaskInstanceId
if ($null -ne $completionEvent) {
break
}
Start-Sleep -Milliseconds 500
}
if ($null -ne $completionEvent) {
$endTime = $completionEvent.Event.TimeCreated.ToString('yyyy-MM-dd HH:mm:ss')
$resultCode = if ($completionEvent.Event.Id -eq 201) {
[string]$completionEvent.EventData.ResultCode
}
else {
'unavailable'
}
Write-WrapperLog -LogPath $FinalizerLogPath -Message "Scheduled task history completion recorded for '$TaskName'. Instance: $TaskInstanceId. End time: $endTime. EventId: $($completionEvent.Event.Id). Result code: $resultCode."
}
else {
Write-WrapperLog -LogPath $FinalizerLogPath -Message "Scheduled task history completion entry was not found within the polling window for '$TaskName'. Instance: $TaskInstanceId." -Level WARN
}
exit 0
}
$resolvedLogPath = Get-EffectiveLogPath -Directory $LogDirectory -FileName $LogFileName
try {
if (-not (Test-Path -LiteralPath $ScriptPath -PathType Leaf)) {
throw "Target script not found at '$ScriptPath'."
}
$taskContext = Get-ScheduledTaskContextForCurrentProcess
$hostPath = (Get-Process -Id $PID -ErrorAction Stop).Path
$startInfo = [System.Diagnostics.ProcessStartInfo]::new()
$startInfo.FileName = $hostPath
$startInfo.UseShellExecute = $false
$startInfo.CreateNoWindow = $true
[void]$startInfo.ArgumentList.Add('-NoProfile')
[void]$startInfo.ArgumentList.Add('-NonInteractive')
[void]$startInfo.ArgumentList.Add('-ExecutionPolicy')
[void]$startInfo.ArgumentList.Add('Bypass')
[void]$startInfo.ArgumentList.Add('-File')
[void]$startInfo.ArgumentList.Add($ScriptPath)
[void]$startInfo.ArgumentList.Add('-LogDirectory')
[void]$startInfo.ArgumentList.Add((Split-Path -Path $resolvedLogPath -Parent))
[void]$startInfo.ArgumentList.Add('-LogFileName')
[void]$startInfo.ArgumentList.Add((Split-Path -Path $resolvedLogPath -Leaf))
$startInfo.EnvironmentVariables['SET_EXTERNAL_MONITOR_INVOCATION_MODE'] = if ($null -ne $taskContext) { 'ScheduledTask' } else { 'Interactive' }
$startInfo.EnvironmentVariables['SET_EXTERNAL_MONITOR_INVOCATION_REASON'] = 'Invocation context was forwarded by Invoke-SetExternalMonitorStateTaskWrapper.ps1.'
$startInfo.EnvironmentVariables['SET_EXTERNAL_MONITOR_WRAPPER_PROCESS_ID'] = [string]$PID
$startInfo.EnvironmentVariables['SET_EXTERNAL_MONITOR_WRAPPER_PROCESS_NAME'] = [string](Get-Process -Id $PID -ErrorAction Stop).ProcessName
if ($null -ne $taskContext) {
$startInfo.EnvironmentVariables['SET_EXTERNAL_MONITOR_TASK_NAME'] = [string]$taskContext.TaskName
$startInfo.EnvironmentVariables['SET_EXTERNAL_MONITOR_TASK_INSTANCE_ID'] = [string]$taskContext.TaskInstanceId
$startInfo.EnvironmentVariables['SET_EXTERNAL_MONITOR_TASK_ACTION_NAME'] = [string]$taskContext.TaskActionName
$startInfo.EnvironmentVariables['SET_EXTERNAL_MONITOR_TASK_START_TIME'] = $taskContext.TaskStartTime.ToString('o')
$startInfo.EnvironmentVariables['SET_EXTERNAL_MONITOR_TASK_LAUNCH_TIME'] = $taskContext.TaskLaunchTime.ToString('o')
$startInfo.EnvironmentVariables['SET_EXTERNAL_MONITOR_TASK_TRIGGER_SOURCE'] = [string]$taskContext.TaskTriggerSource
$startInfo.EnvironmentVariables['SET_EXTERNAL_MONITOR_TASK_TRIGGER_REASON'] = [string]$taskContext.TaskTriggerReason
}
foreach ($argument in @($ScriptArguments)) {
if ($null -eq $argument) {
continue
}
[void]$startInfo.ArgumentList.Add([string]$argument)
}
$childProcess = [System.Diagnostics.Process]::new()
$childProcess.StartInfo = $startInfo
[void]$childProcess.Start()
$childProcess.WaitForExit()
$exitCode = $childProcess.ExitCode
$exitLogLevel = if ($exitCode -ne 0) { 'WARN' } else { 'INFO' }
Write-WrapperLog -LogPath $resolvedLogPath -Message "Child monitor-state script exited with code $exitCode." -Level $exitLogLevel
if ($null -ne $taskContext) {
Start-TaskHistoryFinalizer -TaskName $taskContext.TaskName -TaskInstanceId $taskContext.TaskInstanceId -LogPath $resolvedLogPath
}
exit $exitCode
}
catch {
Write-WrapperLog -LogPath $resolvedLogPath -Message "Wrapper failed. $($_.Exception.Message)" -Level ERROR
exit 1
}