What is the syntax to subscribe to an object's static event in PowerShell?

橙三吉。 提交于 2020-05-10 14:26:52

问题


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

UPDATE: Correct syntax for TimeChanged:

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

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

$networkInformation = [System.Net.NetworkInformation.NetworkChange];
$networkAddressChanged = Register-ObjectEvent -InputObject $networkInformation 
-EventName 'NetworkAddressChanged' 
-Action { Write-Host "NetworkAddressChanged event signaled" }

回答1:


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 a type may have, you can use Get-Member with the -Static switch

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

EDIT: I did notice when trying to access [Microsoft.Win32.SystemEvents] events, that I needed to be running in an elevated prompt (on Vista and above) in order to access the messages.




回答2:


Steven's got the right answer so no need to vote on this (vote on his instead). I just wanted to post a sample snippet that folks can use to play around with static events such that you don't have to find a BCL static event that's easy to fire. :-)

$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


来源:https://stackoverflow.com/questions/2335623/what-is-the-syntax-to-subscribe-to-an-objects-static-event-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!