Skip to content

Instantly share code, notes, and snippets.

@lazywinadmin
Created December 22, 2014 23:51
Show Gist options
  • Save lazywinadmin/d58120e864cacef3e829 to your computer and use it in GitHub Desktop.
Save lazywinadmin/d58120e864cacef3e829 to your computer and use it in GitHub Desktop.
Execute parallel powershell thread using runspace objects
function ForEach-Parallel
{
<#
.DESCRIPTION
.SYNOPSIS
.NOTES
Source: http://powertoe.wordpress.com/2012/05/03/foreach-parallel/
.EXAMPLE
(0..50) |ForEach-Parallel -MaxThreads 4{
$_
sleep (Get-Random -Minimum 0 -Maximum 5)
}
#>
[CmdletBinding()]
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
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment