Created
November 8, 2021 15:02
-
-
Save OtterKring/3830dd4340d20e91da918f27553053d2 to your computer and use it in GitHub Desktop.
emulate functions in foreach parallel
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
# 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