Sukram22
Sukram22

Reputation: 123

Pass variables to Foreach-Object PowerShell 7

What I want:

I have a script, which copies CAB-Files to over a hundred Servers, and works with it on them. This script runs for over a week. As I learned about the Foreach-Object -parallel Feature, I thought this would speed up the script considerably. But I ran into a problem. Since I am not very PowerShell knowledgeable, and I didn't find a post about this problem anywhere, I thought, I going to try my luck and ask here:

Expected and actual results

I want to pass a variable to the executed scriptblock in the foreach-object cmdlet, like here:

$test = "123"
1..3|foreach-object -parallel {param($test);echo "$_, $test"} -ArgumentList($test)

What I expect:

1, 123
2, 123
3, 123

What I get:

ForEach-Object: Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be used together or an insufficient number of parameters were provided.

What am I doing wrong?

It might be an trivial problem. But since I don't get anywhere and don't find any post/code example. I post it here. I am thankful for answers.

Upvotes: 12

Views: 9465

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58931

You can simplify that by using the using keyword :-)

$test = "123"
1..3 | foreach-object -parallel { echo "$_, $($using:test)" } 

Upvotes: 22

Related Questions