Object events

As we mentioned, object events are the bread and butter of developers, but that doesn't mean that operations people shouldn't be using them. One such event that is quite useful in an enterprise scenario is an event log subscription. In a running PowerShell session, you can attach to the event log and subscribe certain events, for example, all events in the application log with ID 1001 and the source Windows Error Reporting. Now, each time an event is generated on the system, the event log listener in your session kicks off and processes the event when it is written to the event log:

$eventLogQuery = @"
<QueryList>
<Query Id="0" Path="Application">
<Select Path="Application">*[System[(EventID=1001)]]</Select>
</Query>
</QueryList>
"@

# Relies on full .NET Framework - Use Windows PowerShell
$queryObject = [System.Diagnostics.Eventing.Reader.EventLogQuery]::new('Application','LogName',$eventLogQuery)
$watcher = [System.Diagnostics.Eventing.Reader.EventLogWatcher]::new($queryObject)

Register-ObjectEvent -InputObject $watcher -EventName EventRecordWritten -Action {
$eventEntry = $event.SourceEventArgs
$eventEntry.EventRecord | Out-Host # Take a look at your event's properties
}

$watcher.Enabled = $true

# Now everytime such an event is logged, the watcher will trigger and execute your script block.

In order to register for events, the Register-ObjectEvent cmdlet is used. It takes the object in question and the name of the event. You can, for example, use Get-Member -MemberType Event to explore which events your object offers. Another great source is the .NET API reference, which also offers descriptive text and code samples.

Review get-help about_Automatic_Variables to find out about the built-in variables such as $event and $sender.

Whenever the EventRecordWritten event is received and the watcher is enabled, the events will go through the script block. Inside the script block, we can use built-in variables such as $Event and $EventArgs to work with the object that raised the event itself. In our case, the object is a System.Diagnostics.Eventing.Reader.EventRecord object, which you have full access to.

For object events, the best source of documentation is the .NET API reference. This is the easiest way to work with the object that raised the event and to see the type used and its properties. While in .NET you need to cast your sender object to the target type, PowerShell at least does this automatically.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.196.217