在运行时自动从 PowerShell 作业中提取数据 [英] Automatically pulling data from a PowerShell job while running

查看:28
本文介绍了在运行时自动从 PowerShell 作业中提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试做一些很可能超出 PowerShell 的方法时,我似乎遇到了一堵砖墙.我有一个主窗体脚本,它编排了我的大部分功能,但我需要另一个脚本来打开一个侦听器(system.Net.Sockets.Udpclient.Receive),并在整个程序运行过程中不断向主窗体中的文本框输入信息.在我的一生中,我无法摆脱这种让工作受苦的愚蠢的非儿童环境;没有点源,没有全局范围的变量,什么都没有.我可以在其上放置一个对象侦听器以完成状态更改,然后打开另一个侦听器并尝试以这种方式进行调整,但它会变得非常混乱且不可靠.

While trying to do something quite possibly beyond the means of PowerShell I seem to have ran into a brick wall. I have a main form script, which orchestrates most of my functions but I need another script to open a listener (system.Net.Sockets.Udpclient.Receive) and keep feeding in information to a textbox in the main form throughout the entire program's running. For the life of me I can't get around this daft non-child environment that jobs suffer from; no dot sourcing, no global scoped variables, nothing. I can put an object-listener on it for statechanged to completion and then open another listener and try and bodge this way but it will get very messy and unreliable.

作为一种解决方法,我希望使用 TCP/UDP 侦听器,它不会挂起应用程序以获取响应、拉取 hasmoredata 的事件或从作业中更新主脚本中的文本框的方法.

As a workaround I would love a TCP/UDP listener which doesn't hang the application for a response, an event to pull on hasmoredata or a way of updatign the textbox in the main script from within the job.

推荐答案

您可以通过引发事件并将其转发回本地会话来从作业中返回数据.

You can return data from a job by raising an event and forwarding it back to the local session.

这是一个例子:

 $job = Start-Job -Name "ReturnMessage" -ScriptBlock {
     # forward events named "MyNewMessage" back to job owner
     # this even works across machines
     Register-EngineEvent -SourceIdentifier MyNewMessage -Forward

     while($true) {
         sleep 2
         $i++
         $message = "This is message $i."
         # raise a new progress event, assigning to $null to prevent
         # it ending up in the job's output stream
         $null = New-Event -SourceIdentifier MyNewMessage -MessageData $message
     }
 }

$event = Register-EngineEvent -SourceIdentifier MyNewMessage -Action {
    Write-Host $event.MessageData -ForegroundColor Green
}

<# Run this to stop job and event listner
$job,$event| Stop-Job -PassThru| Remove-Job
#>

请注意,您仍然可以在作业运行时在提示符处键入.执行块注释中的代码以停止作业和事件侦听器.

Note that you can still type at the prompt while the job is running. Execute the code in the block comments to stop the job and event listner.

这篇关于在运行时自动从 PowerShell 作业中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆