Skip to content

Instantly share code, notes, and snippets.

@gitfvb
Created December 19, 2022 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gitfvb/00f2d604d11c3004b23152cd90e9b1e9 to your computer and use it in GitHub Desktop.
Save gitfvb/00f2d604d11c3004b23152cd90e9b1e9 to your computer and use it in GitHub Desktop.
Example of parallel loops in powershell core with variables AND functions
# Define the function to use
Function Times-Two {
param($j)
$j*2
}
# Define all functions you want to load into parallel runspaces
# The reason to do this is that functions are not available in the runspaces like variables
$functionsArr = @("Times-Two")
# Load all functions into a variable
$functionsObj = [PSCustomObject]@{}
$functionsArr | ForEach {
$func = Get-Command -Name $_
$functionsObj | Add-Member -MemberType NoteProperty -Name $func.Name -Value $func.Definition.toString()
}
# Start the parallel loop
1..5 | ForEach-Object -ThrottleLimit 5 -Parallel {
# Load the functions into the runspace, all other variables than the input need $using: as prefix
$using:functionsObj.PSObject.Properties | ForEach {
$functionsMember = $_
# Creating a string consisting of "Function", the function name and the definition
. { Invoke-Expression "Function $( $functionsMember.Name ) { $( $functionsMember.Value ) }" }
}
# Use the input object
$i = $_
# Do something with the input object and loaded functions
Write-Host "Hello World $( Times-Two $i )"
# Show the duration with parallelisation
Start-Sleep 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment