简体   繁体   English

将C#代码转换为PowerShell

[英]Convert C# code to PowerShell

Given this piece of code: 鉴于这段代码:

someobject.ProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage);

How could I write the same thing in powershell, i used Register-Event but when i called the execute method on the object it just blocks the thread and you only see that the event has fired after the action is finished, I also tried to use Start-Job. 我怎么能在powershell中编写相同的东西,我使用了Register-Event但是当我在对象上调用execute方法时它只是阻塞线程而你只看到事件在动作完成后被触发了,我也尝试使用启动工作。

Any ideas? 有任何想法吗?

Register-ObjectEvent should work: Register-ObjectEvent应该工作:

Register-ObjectEvent -InputObject $someobject -EventName ProgressChanged `
    -Action { Write-Host $EventArgs.ProgressPercentage }

See this TechNet article for more information about asynchronous event handling in PowerShell. 有关PowerShell中异步事件处理的更多信息,请参阅此TechNet文章

EDIT: As requested in comments, here is the code I used in my tests: 编辑:根据评论中的要求,这是我在测试中使用的代码:

$timer = New-Object System.Timers.Timer
$timer.Interval = 500
$timer.AutoReset = $true
Register-ObjectEvent -InputObject $timer -EventName Elapsed `
    -Action { Write-Host $EventArgs.SignalTime }
$timer.Start()

From there on, the signal times of the Elapsed events were printed to the console every half second until I managed to blind-type $timer.Stop() . 从那时起, Elapsed事件的信号时间每半秒打印到控制台,直到我设法盲目输入$timer.Stop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM