Reacting to events

Events in .NET occur when something of interest happens to an object. For instance, System.IO.FileSystemWatcher can be used to monitor a filesystem for changes; when something changes, an event will be raised.

Many different types of objects raise events when changes occur. Get-Member can be used to explore an instance of an object for Event members. For example, a Process object returned by the Get-Process command includes a number of events, shown as follows:

PS> Get-Process | Get-Member -MemberType Event

TypeName: System.Diagnostics.Process

Name MemberType Definition
---- ---------- ----------
Disposed Event System.EventHandler Disposed(System.Object, System.EventArgs)
ErrorDataReceived Event System.Diagnostics.DataReceivedEventHandler ErrorDataReceived(S...
Exited Event System.EventHandler Exited(System.Object, System.EventArgs)
OutputDataReceived Event System.Diagnostics.DataReceivedEventHandler OutputDataReceived(...

PowerShell can react to these events, executing code when an event occurs.

This section uses the events raised by FileSystemWatcher to demonstrate working with events. FileSystemWatcher is able to react to a number of different events, shown as follows:

PS> [System.IO.FileSystemWatcher]::new() | Get-Member -MemberType Event | Select-Object Name

Name
----
Changed
Created
Deleted
Disposed
Error
Renamed

The Changed and Created events will be used in the following examples.

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

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