3

I have multiple commands run in parallel in separate runspaces, managed by a RunspacePool.

How can I determine the runspace each command is running in?

param (
    $MaxRunspaces = 4,
    $JobCount = 20
)
try {
    $pool = [RunspaceFactory]::CreateRunspacePool(1, $MaxRunspaces)
    $pool.Open()
    $jobs = 1..$JobCount | foreach {
        $ps = [PowerShell]::Create()
        $ps.RunspacePool = $pool
        [void]$ps.AddScript({
            # get current runspace here ???
            # $runspace = ...
        })
        [PSCustomObject]@{
            PowerShell = $ps
            AsyncResult = $ps.BeginInvoke()
        }
    }
    $jobs | foreach {
        $_.PowerShell.EndInvoke($_.AsyncResult)
        $_.PowerShell.Dispose()
    }
}
finally {
    $pool.Dispose()
}
marsze
  • 15,079
  • 5
  • 45
  • 61
  • I might be wrong but I think you would need to do something like `$PSInstance = [powershell]::Create().AddScript({....}).AddParameter(....)` and then `[PSCustomObject]@{Instance = $PSinstance`. Look at Mathias example from [this question](https://stackoverflow.com/questions/41796959/why-powershell-workflow-is-significantly-slower-than-non-workflow-script-for-xml). – Santiago Squarzon Aug 11 '21 at 17:30
  • @SantiagoSquarzon This does not tell me the runspace, also there are more ps instances than runspaces. – marsze Aug 12 '21 at 09:45

0 Answers0