Last active
January 23, 2020 16:14
-
-
Save jonathanmedd/cb4040a9e22f08ded8fca0909b84d027 to your computer and use it in GitHub Desktop.
PowerShell Runspace Example GitHubUsers
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
# Modified Example From: https://blog.netnerds.net/2016/12/runspaces-simplified/ | |
$users = Invoke-RestMethod -Uri 'https://api.github.com/users' | |
$pool = [RunspaceFactory]::CreateRunspacePool(1, 5) | |
$pool.ApartmentState = "MTA" | |
$pool.Open() | |
$runspaces = @() | |
$scriptblock = { | |
Param ( | |
[string]$login, | |
[string]$id | |
) | |
Write-Output "GitHub User $login has ID $id" | |
$Seconds = (Get-Random -Minimum 1 -Maximum 10) | |
Start-Sleep -Seconds $Seconds | |
} | |
$users | ForEach-Object { | |
$runspace = [PowerShell]::Create() | |
$null = $runspace.AddScript($scriptblock) | |
$null = $runspace.AddArgument($_.login) | |
$null = $runspace.AddArgument($_.id) | |
$runspace.RunspacePool = $pool | |
$runspaces += [PSCustomObject]@{ Pipe = $runspace; Status = $runspace.BeginInvoke() } | |
} | |
while ($runspaces.Status -ne $null){ | |
$completed = $runspaces | Where-Object { $_.Status.IsCompleted -eq $true } | |
foreach ($runspace in $completed){ | |
$runspace.Pipe.EndInvoke($runspace.Status) | |
$runspace.Status = $null | |
} | |
} | |
$pool.Close() | |
$pool.Dispose() | |
GitHub User defunkt has ID 2 | |
GitHub User wycats has ID 4 | |
GitHub User mojombo has ID 1 | |
GitHub User ezmobius has ID 5 | |
GitHub User evanphx has ID 7 | |
GitHub User vanpelt has ID 17 | |
GitHub User ivey has ID 6 | |
GitHub User pjhyett has ID 3 | |
GitHub User brynary has ID 19 | |
GitHub User kevinclark has ID 20 | |
GitHub User technoweenie has ID 21 | |
GitHub User wayneeseguin has ID 18 | |
GitHub User topfunky has ID 26 | |
GitHub User macournoyer has ID 22 | |
GitHub User takeo has ID 23 | |
GitHub User anotherjesse has ID 27 | |
GitHub User roland has ID 28 | |
GitHub User fanvsfan has ID 30 | |
GitHub User caged has ID 25 | |
GitHub User lukas has ID 29 | |
GitHub User tomtt has ID 31 | |
GitHub User jamesgolick has ID 37 | |
GitHub User nitay has ID 34 | |
GitHub User railsjitsu has ID 32 | |
GitHub User KirinDave has ID 36 | |
GitHub User mojodna has ID 45 | |
GitHub User kevwil has ID 35 | |
GitHub User atmos has ID 38 | |
GitHub User bmizerany has ID 46 | |
GitHub User errfree has ID 44 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment