Created
October 24, 2018 14:11
-
-
Save adamfortuno/3118e0057bb98ac66fecaf794a5aea3c to your computer and use it in GitHub Desktop.
Execute the same scriptblock several times in parallel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Invoke-Tasks { | |
<# | |
.Synopsis | |
Invoke a Task | |
.Description | |
Executes a task with different calls in parallel. | |
.Parameter TaskScript | |
The script for the task to be executed. | |
.Parameter Parameters | |
An array of hash tables. Each hash table provides | |
parameter values used in a seperate run of the task. | |
.Parameter Throttle | |
The maximum number of parallel executions of this | |
task. | |
.Example | |
$task_script = { | |
param($name, $age) | |
"$name is $age years old." >> c:\"temp\${name}.txt" | |
} | |
$task_parameters = @( | |
@{'name' = 'Ross'; 'age' = 28} | |
@{'name' = 'Riley'; 'age' = 23} | |
@{'name' = 'Simone'; 'age' = 31} | |
) | |
Invoke-Tasks -TaskScript $task_script -Parameters $task_parameters | |
#> | |
Param( | |
[Parameter(Mandatory=$true,Position=1)][scriptblock]$TaskScript | |
, [Parameter(Mandatory=$true,Position=2)][Hashtable[]]$Parameters | |
, [Parameter(Mandatory=$false,Position=3)][int] $Throttle = 3 | |
) | |
[pscustomobject[]]$threads_all = @() | |
[runspacefactory]::CreateRunspacePool() | Out-Null | |
$runspace_pool = [runspacefactory]::CreateRunspacePool(1, $Throttle) | |
$runspace_pool.ApartmentState = "STA" | |
$runspace_pool.Open() | |
for ($iterator = 0; $iterator -le $Parameters.Count - 1; $iterator++) { | |
$session = [Powershell]::Create() | |
$session.AddScript($TaskScript, $false) | Out-Null | |
$session.AddParameters($Parameters[$iterator]) | Out-Null | |
$session.RunspacePool = $runspace_pool | |
$thread_created = [pscustomobject]@{ | |
'session' = $session | |
'thread_handle' = $session.BeginInvoke() | |
'IsActive' = $True | |
} | |
$threads_all += $thread_created | |
} | |
Write-Output -NoEnumerate -InputObject $threads_all | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment