Powershell Backgroundworker

荒凉一梦 提交于 2019-12-24 17:24:35

问题


Can anyone give me an example of how to use BackgroundWorker in Powershell?

I want to write something so when a new tab is selected in my Powershell GUI app, it will switch to the tab with a "please wait" message displayed, then run some checks in a BackgroundWorker thread, and then update.

Is this possible in Powershell? All the Googling I've done points to c# or VB.Net.

Cheers,

Ben


回答1:


If the background thread is going to use a PowerShell pipeline to do its work, then I would avoid using BackgroundWorker. It wouldn't be tied to a PowerShell Runspace. Try doing your async processing using Register-ObjectEvent e.g.:

Register-ObjectEvent $tabItem Loaded -Action { <do bg work here> }



回答2:


You could also use Start-Process:

$scriptPath = "c:\script.ps1"
$allArgs = "/someOrNoArgsHere /moreArgs"
$backgroundProcess = Start-Process -FilePath $scriptPath -ArgumentList $allArgs -Wait -Passthru -WindowStyle Hidden
$backgroundProcess.WaitForExit()
$backgroundProcess.ExitCode

Or you could use a one-liner:

Start-Process -FilePath "c:\script.ps1" -ArgumentList "/someOrNoArgsHere /moreArgs" -Wait -Passthru -WindowStyle Hidden


来源:https://stackoverflow.com/questions/3969793/powershell-backgroundworker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!