-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06a - Foreachparallel.ps1
More file actions
44 lines (44 loc) · 1.54 KB
/
06a - Foreachparallel.ps1
File metadata and controls
44 lines (44 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
function ForEach-Parallel {
param(
[Parameter(Mandatory=$true,position=0)]
[System.Management.Automation.ScriptBlock] $ScriptBlock,
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[PSObject]$InputObject,
[Parameter(Mandatory=$false)]
[int]$MaxThreads=5
)
BEGIN {
$iss = [system.management.automation.runspaces.initialsessionstate]::CreateDefault()
$pool = [Runspacefactory]::CreateRunspacePool(1, $maxthreads, $iss, $host)
$pool.open()
$threads = @()
$ScriptBlock = $ExecutionContext.InvokeCommand.NewScriptBlock("param(`$_)`r`n" + $Scriptblock.ToString())
}
PROCESS {
$powershell = [powershell]::Create().addscript($scriptblock).addargument($InputObject)
$powershell.runspacepool=$pool
$threads+= @{
instance = $powershell
handle = $powershell.begininvoke()
}
}
END {
$notdone = $true
while ($notdone) {
$notdone = $false
for ($i=0; $i -lt $threads.count; $i++) {
$thread = $threads[$i]
if ($thread) {
if ($thread.handle.iscompleted) {
$thread.instance.endinvoke($thread.handle)
$thread.instance.dispose()
$threads[$i] = $null
}
else {
$notdone = $true
}
}
}
}
}
}