Skip to content

Instantly share code, notes, and snippets.

@OtterKring
Created November 8, 2021 15:02
Show Gist options
  • Save OtterKring/3830dd4340d20e91da918f27553053d2 to your computer and use it in GitHub Desktop.
Save OtterKring/3830dd4340d20e91da918f27553053d2 to your computer and use it in GitHub Desktop.
emulate functions in foreach parallel
# create the code usually written as function as scriptblock
# it can be run directly in the main script as any other scriptblock
$loopcode = {
param($user,$counter)
write-host ("User: {0} {1}" -f $user,$counter)
}
# convert the scriptblock to string to be able to reuse it in foreach -parallel
# functions cannot be used in foreach -parallel
$codestring = [string]$loopcode
# convert the string back to a scriptblock in the loop, add parameters as needed
1..10 | foreach -Parallel {
& ([scriptblock]::Create($using:codestring)) 'me' $_
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment