-
-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathExample-PowerShellRunspaces.ps1
More file actions
49 lines (40 loc) · 1.29 KB
/
Example-PowerShellRunspaces.ps1
File metadata and controls
49 lines (40 loc) · 1.29 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
45
46
47
48
49
$watch = [System.Diagnostics.Stopwatch]::StartNew()
$pool = [RunspaceFactory]::CreateRunspacePool(1, [int]$env:NUMBER_OF_PROCESSORS+1)
$pool.ApartmentState = "MTA"
$pool.Open()
$runspaces = [System.Collections.ArrayList]@()
$scriptblock = {
param(
$Guid
)
$guid
}
function New-Runspace {
$runspace = [PowerShell]::Create()
$null = $runspace.AddScript($scriptblock)
$null = $runspace.AddArgument([guid]::NewGuid())
$runspace.RunspacePool = $pool
$runspace
}
$initialRunspace = New-Runspace
$runspaces.Add([PSCustomObject]@{ Pipe = $initialRunspace; Status = $initialRunspace.BeginInvoke() }) > $null
$count = 0
while ($runspaces.Count -gt 0) {
foreach($currentRunspace in $runspaces.ToArray()) {
if($currentRunspace.Status.IsCompleted) {
if($count -lt 1001) {
$runspace = New-Runspace
$count++
$runspaces.Add([PSCustomObject]@{ Pipe = $runspace; Status = $runspace.BeginInvoke() }) > $null
}
$results = $currentRunspace.Pipe.EndInvoke($currentRunspace.Status)
$currentRunspace.Pipe.Dispose()
$runspaces.Remove($currentRunspace)
$results
}
}
}
$pool.Close()
$pool.Dispose()
$watch.Stop()
$watch.ElapsedMilliseconds / 1000