Configure from PowerShell a script run when event occurs

Yes, this is exactly what I want (probably not the handiest solution, but it’s ok).

After checking your link, I tried to modify my script accordingly. PowerShell generates an error with $watcher.EnableRaisingEvents = $true (“The property cannot be found for this object”), so my code simply is:

$logName = 'Security'
$select = "*[System[Provider[@Name='Microsoft-Windows-Kernel-Power'] and (EventID=105)]]"
$query = [System.Diagnostics.Eventing.Reader.EventLogQuery]::new($logName, [System.Diagnostics.Eventing.Reader.PathType]::LogName, $select)

$watcher = [System.Diagnostics.Eventing.Reader.EventLogWatcher]::new($query)

$action = {
    Write-Host "Action triggered"
    "Action triggered" | Out-File C:\out.txt
}

Register-ObjectEvent -InputObject $watcher -EventName 'EventRecordWritten' -Action $action

$watcher.Enabled = $true

do
{
    Wait-Event -Timeout 1
    Write-Host "." -NoNewline
} while ($true)

Write-Host "bye"

If I run the script, this output is produced:

PS C:\> .\test_script_1.ps1

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
2      5f26f7ab-6310-…                 NotStarted    False                                …
Action triggered
....................

Some doubts:

  • the object being printed (even if I did not explicitly printed it in the script) is a job? Or what else?
  • The “Action triggered” string is printed when the script is launched and it is unrelated to the Event 105, while instead it should.
  • If, during the execution of the script, I connect the power cable (so I trigger Event 105) nothing happens and the dots keep being printed.

IIUC, Wait-Event should instead react to the Event 105.
What is still wrong?

Ok, I got your point, but for now I would like to focus on the above solution instead.