因为我的雇主不想使用编译的软件,所以他们要求我创建一个GUI,以使用PowerShell并行ping一系列设备。我的PowerShell脚本由一个ping设备上的一个Form和一个Button组成。为了防止GUI锁定,我使用运行空间将ping操作卸载到单独的线程。我能够ping设备并使用Runspace中的信息更新Form,但是当我完成应用程序后,我无法关闭/处置Runspace,因此即使在应用程序退出后,Runspace仍能继续运行。
下面提供的功能ping localhost十次,并将结果添加到GUI中的ListView。
Function PingDevices
{
Write-Host "Pinging Devices"
$items = $StorePingInfo_ListView.Items
$ScriptBlock =
{
$a = 0
for(;$a -lt 10; $a++)
{
$PingResult = Test-Connection 127.0.0.1 -Count 1
#[System.Windows.Forms.MessageBox]::Show($PingResult)
$items.Add("Name").SubItems.Add($PingResult)
sleep 1
}
}
$runspace = [RunspaceFactory]::CreateRunspace()
$runspace.Open()
$runspace.SessionStateProxy.SetVariable('Items',$items)
$powershell = [System.Management.Automation.PowerShell]::create()
$powershell.Runspace = $runspace
$powershell.AddScript($ScriptBlock)
$AsyncHandle = $powershell.BeginInvoke()
}
Function CleanupResources
{
#When I try to clean up the resources I get Null errors
Write-Host "AsyncHandle is Null = "($AsyncHandle -eq $null)
$data = $powershell.EndInvoke($AsyncHandle)
$powershell.Dispose()
$runspace.Close()
}
关闭应用程序时出现的错误是
ping设备 AsyncHandle为Null = True 您不能在空值表达式上调用方法。 在C:\ Users \ Loligans \ Drive \ dboardscript.ps1:673 char:5 + $ data = $ powershell.EndInvoke($ AsyncHandle) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo:InvalidOperation:(:) [],RuntimeException + FullyQualifiedErrorId:InvokeMethodOnNull 您不能在空值表达式上调用方法。 在C:\ Users \ Loligans \ Drive \ dboardscript.ps1:674 char:5 + $ powershell.Dispose() + ~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo:InvalidOperation:(:) [],RuntimeException + FullyQualifiedErrorId:InvokeMethodOnNull 您不能在空值表达式上调用方法。 在C:\ Users \ Loligans \ Drive \ dboardscript.ps1:675 char:5 + $ runspace.Close() + ~~~~~~~~~~~~~~~~~ + CategoryInfo:InvalidOperation:(:) [],RuntimeException + FullyQualifiedErrorId:InvokeMethodOnNull
我认为该问题正在发生,因为运行空间正在执行,但是在运行空间未运行时也会发生。但是,当它们全部耦合到同一个函数中时,它将成功关闭且没有错误
Function PingDevices
{
Write-Host "Pinging Devices"
$items = $StorePingInfo_ListView.Items
$ScriptBlock =
{
$a = 0
for(;$a -lt 10; $a++)
{
$PingResult = Test-Connection 127.0.0.1 -Count 1
#[System.Windows.Forms.MessageBox]::Show($PingResult)
$items.Add("Name").SubItems.Add($PingResult)
sleep 1
}
}
$runspace = [RunspaceFactory]::CreateRunspace()
$runspace.Open()
$runspace.SessionStateProxy.SetVariable('Items',$items)
$powershell = [System.Management.Automation.PowerShell]::create()
$powershell.Runspace = $runspace
$powershell.AddScript($ScriptBlock)
$AsyncHandle = $powershell.BeginInvoke()
$data = $powershell.EndInvoke($AsyncHandle)
$powershell.Dispose()
$runspace.Close()
}
如何获得运行空间以释放其驻留的同一功能之外的所有资源?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句