What is the syntax for subscribing to a static event of an object in PowerShell?

Register-ObjectEvent looks for an instance of the object in the required InputObject parameter. What is the syntax for a static (Shared) object?

UPDATE : correct TimeChanged syntax:

$systemEvents = [Microsoft.Win32.SystemEvents] $timeChanged = Register-ObjectEvent -InputObject $systemEvents -EventName 'TimeChanged' -Action { Write-Host "Time changed" } 

Unfortunately, SystemEvents will not be signaled in PowerShell ISE. Here's a sample using an object static event that works everywhere:

 $networkInformation = [System.Net.NetworkInformation.NetworkChange]; $networkAddressChanged = Register-ObjectEvent -InputObject $networkInformation -EventName 'NetworkAddressChanged' -Action { Write-Host "NetworkAddressChanged event signaled" } 
+6
events powershell
source share
2 answers

If you assign a static type to a variable, you can subscribe to static events.

For example:

 $MyStaticType = [MyStaticNamespace.MyStaticClass] Register-ObjectEvent -InputObject $MyStaticType -EventName MyStaticEvent -Action {Write-Host "Caught a static event"} 

To find any static events that a type can have, you can use Get-Member with the -Static switch

 [MyStaticNamespace.MyStaticClass] | get-member -static -membertype event 

EDIT: I noticed that when trying to access events [Microsoft.Win32.SystemEvents] I had to work in an advanced request (in Vista and above) in order to access the messages.

+5
source share
Stephen received the correct answer, so no need to vote on this (vote instead). I just wanted to post a sample snippet that people can use to play with static events, so you don't need to look for a static BCL event that fires easily. :-)
 $src = @' using System; namespace Utils { public static class StaticEventTest { public static event EventHandler Fired; public static void RaiseFired() { if (Fired != null) { Fired(typeof(StaticEventTest), EventArgs.Empty); } } }} '@ $srcId = 'Fired' Add-Type -TypeDefinition $src Unregister-Event -SourceIdentifier $srcId -ea 0 $id = Register-ObjectEvent ([Utils.StaticEventTest]) Fired ` -SourceIdentifier $srcId -Action {"The static event fired"} [Utils.StaticEventTest]::RaiseFired() while (!$id.HasMoreData) { Start-Sleep -Milliseconds 250 } Receive-Job $id 
+2
source share

All Articles