架构师_程序员

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 2470|回复: 3
打印 上一主题 下一主题

PowerShell调用.net并且订阅事件[源码]

[复制链接]
跳转到指定楼层
楼主
发表于 2017-1-17 17:05:59


我用的.net的WebClient对象实现文件的下载,

并且用powershell订阅DownloadProgressChanged的事件,

实现了下载进度条的更新。

订阅事件用到了powershell的Register-ObjectEvent,介绍文档如下:

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

语法
    Register-ObjectEvent [-InputObject] <PSObject> [-EventName] <String> [[-SourceIdentifier] <String>] [[-Action] <ScriptBlock>] [-Forward ] [-MaxTriggerCount <Int32>] [-MessageData <PSObject>] [-SupportEvent ] [<CommonParameters>]


输入
    None
    You cannot pipe objects to Register-ObjectEvent .

输出
    System.Management.Automation.PSEventJob
    This cmdlet does not generate any output.

注释
    * Events, event subscriptions, and the event queue exist only in the current session. If you close the current session, the event queue is discarded and the event subscription is canceled.
   

示例
    Example 1: Subscribe to events when a new process starts
    PS C:\>$Query = New-Object System.Management.WqlEventQuery "__InstanceCreationEvent", (New-Object TimeSpan 0,0,1), "TargetInstance isa 'Win32_Process'"
    PS C:\>$ProcessWatcher = New-Object System.Management.ManagementEventWatcher $Query
    PS C:\>Register-ObjectEvent -InputObject $ProcessWatcher -EventName "EventArrived"
   
    This example subscribes to events generated when a new process starts.

The command uses the ManagementEventWatcher object to get EventArrived events. A query object specifies that the events are instance creation events for the Win32_Process class.
    Example 2: Specify an action to respond to an event
    PS C:\>$Query = New-Object System.Management.WqlEventQuery "__InstanceCreationEvent", (New-Object TimeSpan 0,0,1), "TargetInstance isa 'Win32_Process'"
    PS C:\>$ProcessWatcher = New-Object System.Management.ManagementEventWatcher $query
    PS C:\>$Action = { New-Event "PowerShell.ProcessCreated" -Sender $Sender -EventArguments $EventArgs.NewEvent.TargetInstance }
    PS C:\>register-objectEvent -InputObject $ProcessWatcher -EventName "EventArrived" -Action $Action
    Id    Name            State      HasMoreData     Location             Command
    --    ----            -----      -----------     --------             -------
    2     422cfe5a-65e... Running    True                                 New-Event "PowerShe...
   
    This example shows how to specify an action to respond to an event. When you specify an action, events that are raised are not added to the event queue. Instead, the action responds to the event.

In this example, when an instance creation event is raised indicating that a new process is started, a new ProcessCreated event is raised.

The action uses the $Sender and $EventArgs automatic variables which are populated only for event actions.

The Register-ObjectEvent command returns a job object that represents the action, which runs as a background job. You can use the Job cmdlets, such as Get-Job and Receive-Job, to manage the background job.

For more information, see about_Jobs.
    Example 3: Subscribe to object events on remote computers
    PS C:\>$S = New-PSSession -ComputerName "Server01, Server02"
    PS C:\> Invoke-Command -Session $S -FilePath ProcessCreationEvent.ps1
    PS C:\> Invoke-Command -Session $S { get-event }# ProcessCreationEvent.ps1function Enable-ProcessCreationEvent{   $Query = New-Object System.Management.WqlEventQuery "__InstanceCreationEvent", `
       (New-Object TimeSpan 0,0,1), `
       "TargetInstance isa 'Win32_Process'"   $ProcessWatcher = New-Object System.Management.ManagementEventWatcher $Query   $Identifier = "WMI.ProcessCreated"   Register-ObjectEvent -Input $ProcessWatcher -EventName "EventArrived" `
       -SourceIdentifier $Identifier -MessageData "Test" -Forward}EnableProcessCreationEvent
   
    This example shows how to subscribe to object events on remote computers.

The first command creates PSSessions on two remote computers and saves them in the $S variable.

The second command uses the FilePath parameter of the Invoke-Command cmdlet to run the ProcessCreationEvent.ps1 script in the each of the PSSessions in $S.

The script includes a Register-ObjectEvent command that subscribes to instance creation events on the Win32_Process object through the ManagementEventWatcher object and its EventArrived event.
    Example 4: Use the dynamic module in the PSEventJob object
    PS C:\>$Timer = New-Object Timers.Timer
    PS C:\>$Timer.Interval = 500
    PS C:\>$Job = Register-ObjectEvent -InputObject $Timer -EventName Elapsed -SourceIdentifier Timer.Random -Action {$Random = Get-Random -Min 0 -Max 100}
    PS C:\>$Job.gettype().fullnameSystem.Management.Automation.PSEventJob
    PS C:\>$Job | Format-List -Property *
    State         :
    RunningModule        : __DynamicModule_6b5cbe82-d634-41d1-ae5e-ad7fe8d57fe0
    StatusMessage :
    HasMoreData   : True
    Location      :
    Command       : $Random= Get-Random -Min 0 -Max 100
    JobStateInfo  : Running
    Finished      : System.Threading.ManualResetEvent
    InstanceId    : 88944290-133d-4b44-8752-f901bd8012e2
    Id            : 1
    Name          : Timer.Random
    ChildJobs     : {}... PS C:\>$Timer.Enabled = $True
    PS C:\>& $Job.module {$Random}60
    PS C:\>& $Job.module {$Random}47
   
    This example shows how to use the dynamic module in the PSEventJob object that is created when you include an Action in an event registration.

The first command uses the New-Object cmdlet to create a timer object. The second command sets the interval of the timer to 500 (milliseconds).

The third command uses the Register-ObjectEvent cmdlet to register the Elapsed event of the timer object. The command includes an action that handles the event. Whenever the timer interval elapses, an event is raised and the commands in the action run. In this case, the Get-Random cmdlet generates a random number between 0 and 100 and saves it in the $Randomvariable.

When you use an Action parameter in a Register-ObjectEvent command, the command returns a PSEventJob object that represents the action. The command saves the job object in the $Job variable.

The PSEventJob object that the Register-ObjectEvent cmdlet returns is also available in the Action property of the event subscriber. For more information, see Get-EventSubscriber.

The fourth command shows that the $Job variable contains a PSEventJob object. The fifth command uses the Format-List cmdlet to display all of the properties of the PSEventJob object in a list.

The PSEventJob has a Module property that contains a dynamic script module that implements the action.

The sixth command enables the timer.

The remaining commands use the call operator (&) to invoke the command in the module and display the value of the $Random variable. You can use the call operator to invoke any command in a module, including commands that are not exported. In this case, the commands show the random number that is being generated when the Elapsed event occurs.

For more information about modules, see about_Modules.


RelatedLinks
    Online Version: http://go.microsoft.com/fwlink/?LinkId=821845
    Get-Event
    New-Event
    Register-EngineEvent
    Register-WmiEvent
    Remove-Event
    Unregister-Event
    Wait-Event

最后,附上ps源码吧:

游客,如果您要查看本帖隐藏内容请回复





上一篇:PowerShell单行注释、多行注释、块注释的方法
下一篇:PowerShell利用WebClient下载文件
帖子永久地址: 

架构师_程序员 - 论坛版权1、本主题所有言论和图片纯属会员个人意见,与本论坛立场无关
2、本站所有主题由该帖子作者发表,该帖子作者与架构师_程序员享有帖子相关版权
3、其他单位或个人使用、转载或引用本文时必须同时征得该帖子作者和架构师_程序员的同意
4、帖子作者须承担一切因本文发表而直接或间接导致的民事或刑事法律责任
5、本帖部分内容转载自其它媒体,但并不代表本站赞同其观点和对其真实性负责
6、如本帖侵犯到任何版权问题,请立即告知本站,本站将及时予与删除并致以最深的歉意
7、架构师_程序员管理员和版主有权不事先通知发贴者而删除本文

码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
沙发
发表于 2017-4-26 14:35:44
132432423432423
码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
板凳
发表于 3 天前
2222222222222
码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

免责声明:
码农网所发布的一切软件、编程资料或者文章仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。

Mail To:help@itsvse.com

QQ|Archiver|手机版|小黑屋|架构师 ( 鲁ICP备14021824号-2 )|网站地图

GMT+8, 2019-4-19 05:36

Powered by Discuz! X3.4

© 2001-2014 Comsenz Inc.

快速回复 返回顶部 返回列表