技术上是否可以将Windows中的命令输出到文本框中?
带有测试连接的ping查询在输出中工作得很好(请参阅ping_google屏幕快照)。
如果我更改代码并希望通过测试-netconnection运行查询,则当我发送ICMP测试时什么都不会发生(请参见测试-netConnection屏幕截图)。这是我为此使用的代码。
function trace {
$Trace_Result = Test-NetConnection $textbox_Search_NW_trace.text -informationlevel "detailed"
if($Trace_Result) {
$output_TextBox_NW_trace.Text = ($Trace_Result | Out-String)
} else {
$output_TextBox_NW_trace.Text = "Destination is down"
}
}然后通过按钮调用函数。
$button_Search_NW_trace.Add_Click({trace})发布于 2022-10-08 21:15:56
这似乎是一个表单如何扰乱等待ping响应的.net的问题。我在这个github问题中找到了一个解决问题的方法:
Function trace
{
$oldSyncContext = $null
# alter threading get async ping output back from test-netconnection
try {
$oldSyncContext = [Threading.SynchronizationContext]::Current
[Threading.SynchronizationContext]::SetSynchronizationContext($null)
$output = Test-NetConnection $textbox_Search_NW_trace.text -InformationLevel Detailed |
Format-List |
Out-String
}
finally {
if ($null -ne $oldSyncContext) { [Threading.SynchronizationContext]::SetSynchronizationContext($oldSyncContext) }
}
# write to textbox
$textBoxDisplay.Text = $output
}输出结果如下:

这似乎在较新版本的powershell (7.0.1+)中得到了修正。
https://stackoverflow.com/questions/73994128
复制相似问题