How to run function in different runspace, PowerShell
I have powershell script that add registration to event, but when the event is jump i'm getting the following error every time the event is jump: "no Runspace available to run scripts in this thread" I'm using PS v2, what can i do? Can you provide some code? T开发者_Python百科hanks
It sounds like you're trying to run script on a non-powershell thread, probably via an async callback. This is not a supported scenario. The trick is to "bridge" to callback to the eventing infrastructure, where scriptblocks haev a default runspace. Take a look at what I wrote here:
https://web.archive.org/web/20190222052659/http://www.nivot.org/blog/post/2009/10/09/PowerShell20AsynchronousCallbacksFromNET
It shows you how to work with async threads in powershell and run script in response to callbacks.
-Oisin
Are you in a third party PowerShell host? That's a bug ;)
If you're messing around with Async callbacks, the problem is that you're running in a different thread, and the [Runspace]::DefaultRunspace
is thread static. @x0n wrote a bridge for Async Callbacks awhile back (I'll see if I can find it).
Bottom line, you need to do what the error suggests: provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. But you have to do it FROM the thread where the code is going to execute, so it's a bit rough with async callbacks.
[Management.Automation.Runspaces.Runspace]::DefaultRunspace = [RunspaceFactory]::CreateRunspace()
精彩评论