Tiny PowerShell Project 4 - Setting Event Listener For .NET Events

Tiny PowerShell Project 4 - Setting Event Listener For .NET Events

Subscribes to the events that are generated by a Microsoft .NET Framework object.

There are many .NET events that you could subscribe to and react to these events once emitted. There are some common .NET objects in PowerShell, for which you can set an event listener. How do we find these? To find these events you can use get-member cmdlet to check on the member type of event. Here are some examples:

  1. Timer: The System.Timers.Timer class.

     $timer = New-Object Timers.Timer
     $timer | Get-Member -MemberType Event
    
  2. File System Watcher:

     $watcher = New-Object IO.FileSystemWatcher
     $watcher | Get-Member -MemberType Event
    
  3. Network Events: Various classes related to networking might have events.

     $udpClient = New-Object Net.Sockets.UdpClient
     $udpClient | Get-Member -MemberType Event
    
  4. PowerShell Events: PowerShell objects can also have custom events.

     $eventSubscriber = Register-ObjectEvent -InputObject $yourObject -EventName YourCustomEventName -Action { }
     $eventSubscriber | Get-Member -MemberType Event
    

For today's tiny project, we could consider developing a straightforward script designed to monitor a specified directory for potential modifications. The intended application of this script would be for scenarios where one anticipates the arrival of files from an SFTP server or a shared drive, and subsequent execution of a predefined set of instructions is required. As scheduled jobs may not be suitable when the precise arrival time of the files is uncertain, this script would serve the purpose of monitoring the directory and responding to the associated .NET events triggered by changes in the file system.

$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\Temp"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true

# Specify the path of the text file where the information will be appended
$filePath = "C:\Temp\ChangeLog.txt"

# Register the event and define the action to append the information to the text file
Register-EventObject -InputObject $watcher -EventName "Changed" -Action {
    $path = $EventArgs.FullPath
    $acl = Get-Acl $path
    $owner = $acl.Owner
    $logMessage = "File $path was changed by $owner."
    $logMessage | Out-File -Append -FilePath $filePath
}

To list the subscribed events and unsubscribe from them, you can use the Get-EventSubscriber cmdlet to view the currently registered event subscribers, and the Unregister-Event cmdlet to unsubscribe from specific events.

  1. List Subscribed Events:

You can use the Get-EventSubscriber cmdlet to view a list of currently registered event subscribers in the current PowerShell session. This cmdlet will display information about the event subscribers, including the event name, source identifier, and other details.

Get-EventSubscriber

This command will show you a list of subscribed events along with their details.

  1. Unsubscribe from an Event:

To unsubscribe from a specific event, you can use the Unregister-Event cmdlet. The Unregister-Event cmdlet requires the source identifier of the event subscriber, which you can obtain from the Get-EventSubscriber output.

Here's an example of how to unsubscribe from a specific event:

# Get the list of subscribed events
Get-EventSubscriber

# Replace 'YourEventSourceIdentifier' with the actual source identifier of the event you want to unsubscribe from
Unregister-Event -SourceIdentifier YourEventSourceIdentifier

After running the Unregister-Event cmdlet, the event subscriber with the specified source identifier will be removed, and the event will no longer trigger the associated action.

Keep in mind that when you unsubscribe from an event, you need to provide the correct source identifier for that event. Each event subscriber is identified by a unique source identifier, so make sure you are specifying the correct one to avoid inadvertently removing the wrong event subscriber.

Additionally, if you have registered events with custom PowerShell objects using Register-ObjectEvent, you should ensure to store the event subscription in a variable so that you can later reference it to unsubscribe. For example:

# Register event and store the subscription in a variable
$subscription = Register-ObjectEvent -InputObject $yourObject -EventName YourCustomEventName -Action { }

# To unsubscribe, use the variable containing the event subscription
Unregister-Event -SubscriptionId $subscription.Id

This approach allows you to track and manage the event subscriptions easily.

Some events may not be directly accessible from PowerShell if they are implemented as explicit interface implementations. You can explore events for other .NET objects by creating instances of those objects and running Get-Member -MemberType Event on them.

Did you find this article valuable?

Support Application Support by becoming a sponsor. Any amount is appreciated!