多运行空间 PowerShell/XAML 脚本在单击按钮时崩溃

Multi-Runspace PowerShell/XAML script crashing on button click

我有一个使用异步运行空间的脚本,以便在后台处理内容时显示 XAML/WPF GUI。当我点击按钮时,它崩溃了,但只有在特定状态下才会崩溃。让我详细说明。

该脚本首先对一长串服务器执行 ping 操作,以确保它们正常运行。之后,它会运行一些 SQL 查询、WMI 调用和其他逻辑,处理所有数据,然后使用信息一次一行地更新另一个 window 中我的 DataGrid。

该按钮只会显示 WinForm 确认信息:

#$Global:uihash is my synchronized hashtable.

 $Global:uihash.Button.add_click({if([System.Windows.Forms.MessageBox]::Show `
("Yes or No?", "Question",[System.Windows.Forms.MessageBoxButtons]::OKCancel) -eq "OK")

{Do stuff back in main PS Window}

如果我在脚本对所有设备执行 ping 操作时按下按钮,它会完美运行。如果我在脚本执行期间的任何其他时间单击该按钮,PS Windows 会立即翻转为无响应,我必须杀死它们。

来自应用程序事件日志:

The program PowerShell_ISE.exe version 10.0.10586.117 stopped interacting with Windows and was closed.

我 95% 确定这是因为 ping 设备是脚本中与其他设备完全零交互的唯一部分 window,我只是不知道如何解决这个问题,甚至不知道如何解决解决它。

我想知道是否有人以前见过或经历过这种情况或类似情况,以及您是如何解决的。任何帮助将不胜感激。谢谢!

我一直无法完全解决这个问题,但我确实找到了一个很好的解决方法。我将脚本的主要部分放在 Do-Until 循环中,并让按钮单击更改我创建的全局变量。这打破了循环,关闭了 window,并让所有完成任务 运行 而不会崩溃。

#$Global:uihash is my synchronized hashtable.

#Create synchronized hash table variable
$Global:uiHash.Add(“End”,$false)

 #Create Click Event 
$Global:uihash.Button.add_click({if([System.Windows.Forms.MessageBox]::Show 
("Yes or No?", "Question",[System.Windows.Forms.MessageBoxButtons]::OKCancel) -eq "OK")
{$Global:uiHash.End = $true}

Do {A whole bunch of stuff}
Until ($global:uiHash.end -eq $true)

#Close the window
$Global:uiHash.Window.Dispatcher.Invoke([action]{$Global:uiHash.Window.close() },"Normal")
#Then process the rest of the script