Register-ObjectEvent

Exploring Register-ObjectEvent in PowerShell

Welcome back to Wahmans PowerShell Blog! Today we’re diving into a powerful and often overlooked cmdlet in PowerShell: Register-ObjectEvent. This cmdlet gives you the ability to subscribe to events that are generated by .NET Framework objects, enabling reactive and event-driven scripting. Whether you’re monitoring file system changes or building responsive UI components, Register-ObjectEvent is a valuable tool to have in your PowerShell toolkit.

What is Register-ObjectEvent?

The short description from Microsoft says it all: Subscribes to the events that are generated by a Microsoft .NET Framework object. This means you can attach your script logic to an event, and PowerShell will execute your code when that event is triggered. This allows for event-driven behavior without constant polling or checks.

Let’s break down four example use cases of Register-ObjectEvent, moving from beginner to more advanced!

Example 1: Beginner – Timer-Based Event

This example shows a simple timer that triggers an event every 2 seconds.

$timer = New-Object System.Timers.Timer
$timer.Interval = 2000
$timer.AutoReset = $true

Register-ObjectEvent -InputObject $timer -EventName Elapsed -Action {
    Write-Host "Timer event triggered at: $(Get-Date)"
}

$timer.Start()

# Let the script wait for 10 seconds so we can observe events.
Start-Sleep -Seconds 10
$timer.Stop()

This is a great way to learn about timed events and callback actions.

Example 2: Intermediate – File System Watcher

Monitor directory changes using FileSystemWatcher. Great for automation on file creation!

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

Register-ObjectEvent -InputObject $watcher -EventName Created -Action {
    Write-Host "New file created: $($Event.SourceEventArgs.FullPath)"
}

# Keep running so we can monitor events
Write-Host "Watching C:\Temp for new .txt files for 30 seconds..."
Start-Sleep -Seconds 30

This use case is perfect for automating file-based workflows.

Example 3: Advanced – WMI Event Subscription

Let’s subscribe to a hardware event like USB insertion using WMI. This example listens for any USB drive insertions via WMI.

Register-WmiEvent -Query "SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2" -SourceIdentifier USBInserted -Action {
    Write-Host "A USB drive was inserted at: $(Get-Date)"
}

Write-Host "Listening for USB insert events for 60 seconds..."
Start-Sleep -Seconds 60

# Clean up the event subscription
Unregister-Event -SourceIdentifier USBInserted

This illustrates the power of combining WMI with event handling in PowerShell.

Example 4: Expert – GUI Button Click Event in Windows Forms

This showcases how to tie UI events to PowerShell scripts.

Add-Type -AssemblyName System.Windows.Forms

$form = New-Object System.Windows.Forms.Form
$form.Text = "Click Event Demo"
$form.Size = New-Object System.Drawing.Size(300,200)

$button = New-Object System.Windows.Forms.Button
$button.Text = "Click me!"
$button.Dock = 'Fill'
$form.Controls.Add($button)

Register-ObjectEvent -InputObject $button -EventName Click -Action {
    [System.Windows.Forms.MessageBox]::Show("Button was clicked at $(Get-Date)")
}

$form.ShowDialog()

This advanced example integrates GUI components and event-driven scripting for powerful tools and interfaces!

Wrap-up

Register-ObjectEvent opens up a whole new world of interactivity in PowerShell. From timers and file tags to hardware events and UIs, the only limit is your imagination. Make sure to be careful with long-running scripts, and always unregister your events if needed to avoid memory leaks!

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *