r/PowerShell • u/Prize_Nobody435 • Apr 10 '26
Powershell Runspace help
Hello,
I'm creating a WPF GUI with Powershell v5.
I am running a script in a Runspace when clicking a button.
My question is how do I close the runspace when the script is completed?
I cannot do that with the script that's running in the runspace.
I have tried to put the . close and . dispose at the bottom of the Add_Click event Ave that didn't work either.
Here is my Add_click event command:
search.add_click({
# Create and Open Runspace
$runspace = [runspacefactory]::CreateRunspace()
$runspace.ApartmentState = "STA"
$runspace.Open() $runspace.SessionStateProxy.SetVariable("syncHash", $syncHash)
# Execute Script
$powershell = [powershell]::Create().AddScript($backgroundScript)
$powershell.Runspace = $runspace
$powershell.BeginInvoke()
#$runspace.close()
#$runspace.Dispose()
#$powershell.Dispose()
})
2
u/MechaCola Apr 10 '26
When you create the job, add some meta data about the job status to your synchash table. When you want to close a runspace update the synchash with runspace status so that a while loop is looking for these status changes and disposing them. There should be examples of this on the internet or you could paste what I wrote and AI can take it from there.
5
u/Conscious_Report1439 Apr 10 '26
I hope this helps you big guy!
https://github.com/freedbygrace/Invoke-PSThread
I wrote it some time ago and documented it so it takes the complexity out of getting started with runspaces. Just dot source it to load the function into your session. PM me or hit me up if you need some guidance.
3
u/CognizantAutomaton Apr 11 '26
The runspace can be closed when your WPF window closes.
Maybe this pattern helps:
2
u/nkasco Apr 11 '26
One of my earliest blog posts - https://blog.nkasco.com/wordpress/index.php/2018/05/05/2018-4-25-how-to-build-a-powershell-gui-part-3/