Powershell parallel execution

I needed to fetch data about group members from ActiveDirectory (AD) and import it to csv file. While fetching group member information it has become clear that it would take a lot of time. Problem was that some groups had 100K+ members.

Powershell runspaces came to rescue. Function which I used for parallel processing:

function CallScriptInParallel {
<#
.DESCRIPTION
Foreach data[i] creates a ps shell and executes script
Waits for completion and returns agg result
#>
param($script, $data, $scriptArgs)
Write-Verbose "Parallel work start"
$RunSpacePool = [runspacefactory]::CreateRunspacePool(1, $numOfCores)
$cEvent = New-Object System.Threading.CountDownEvent(1)
if ($RunSpacePool.RunspacePoolStateInfo.State -ne 'Opened') {
$RunSpacePool.Open()
}
WriteLog "Available Runspaces: $($RunSpacePool.GetAvailableRunspaces())"

$jobs = @()
$ps = @()
$wait = @()

$data | foreach {$i = 0} {
$ps += [powershell]::Create()
$ps[$i].runspacepool = $RunSpacePool
$ps[$i].AddScript($script).AddArgument($cEvent).AddArgument($_)
foreach ($arg in $scriptArgs) {
$ps[$i].AddArgument($arg)
}

$jobs += $ps[$i].BeginInvoke()
$wait += $jobs[$i].AsyncWaitHandle

$i++
}
$cEvent.Signal()
$cEvent.Wait()
$cEvent.Dispose()

$result = @()

$ps | foreach {$i = 0} {
#Skip 1st item as it is a task state
$result += $ps[$i].EndInvoke($jobs[$i]) | select -Skip 1
$ps[$i].Dispose()
$i++
}

Write-Verbose "Parallel work done"
return $result
}
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.