Hello there,
It sounds like you want to dispose of the runspace automatically, on completion of the script.
You can set up an event handler for the System.Management.Automation.PowerShell.InvocationStateChanged event, inside of which you can check for the Completed and Failed states and close the runspace then:
Note: Register-ObjectEvent must be used to subscribe to the event; while it is possible in principle to subscribe by passing a script block directly to .add_InvocationStateChanged() on the PowerShell instance, execution will hang when you later call .EndInvoke().
Hope this resolves your Query !!
--If the reply is helpful, please Upvote and Accept it as an answer–