在 PowerShell 中订阅对象的静态事件的语法是什么?
Register-ObjectEvent 在所需参数中查找对象实例输入对象。对象的静态(共享)事件的语法是什么?
$systemEvents = [Microsoft.Win32.SystemEvents]
$timeChanged = Register-ObjectEvent -InputObject $systemEvents
-EventName 'TimeChanged' -Action { Write-Host "Time changed" }
不幸的是,PowerShell ISE 中不会发出系统事件信号。下面是一个使用对象静态事件的示例,该事件在任何地方都适用:
$networkInformation = [System.Net.NetworkInformation.NetworkChange];
$networkAddressChanged = Register-ObjectEvent -InputObject $networkInformation
-EventName 'NetworkAddressChanged'
-Action { Write-Host "NetworkAddressChanged event signaled" }
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" }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果将静态类型分配给变量,则可以订阅静态事件。
例如:
要查找类型可能具有的任何静态事件,您可以使用 Get-Member 和 -Static 开关
编辑:
我确实注意到,当尝试访问 [Microsoft.Win32.SystemEvents] 事件时,我需要在提升的提示符下运行(在 Vista 及更高版本上)才能访问消息。
If you assign a static type to a variable, you can subscribe to static events.
For example:
To find any static events a type may have, you can use Get-Member with the -Static switch
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.
史蒂文得到了正确的答案,因此无需对此进行投票(而是对他的答案进行投票)。我只是想发布一个示例片段,人们可以使用它来处理静态事件,这样您就不必找到易于触发的 BCL 静态事件。 :-)
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. :-)