运行时自动从PowerShell作业中提取数据

运行时自动从PowerShell作业中提取数据

本文介绍了运行时自动从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作业中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 04:29