Why is the foreach-object loop not working in parallel with parameters?

92 views Asked by At

I'm doing a poor-mans load test on a hand full of docker containers, to see if the memory consumption increases and potentially spot memory leaks.

I have a basic, working script:

1..25 | Foreach-Object -ThrottleLimit 5 -Parallel {
    try {
        $Result = Invoke-WebRequest -Uri "http://localhost:3000/foo"
        $StatusCode = $Result.StatusCode
    }
    catch {
        $StatusCode = $_.Exception.Response.StatusCode.value__
    }
    $StatusCode
}

Now, I wanted to add some parameters to make it a tad more flexible:

param(
  [int]$iterations = 25,
  [int]$throttleLimit = 5,
  [string]$targetUri = "http://localhost:3000/foo"
)

1..$iterations | Foreach-Object -ThrottleLimit $throttleLimit -Parallel {
  try {
    $Result = Invoke-WebRequest -Uri $targetUri
    $StatusCode = $Result.StatusCode
  }
  catch {
    $StatusCode = $_.Exception.Response.StatusCode.value__
  }
  $StatusCode
}

The second version immediately exits. Removing the -ThrottleLimit $throttleLimit -Parallel from the foreach statement resolves the issue.

Why is that? I'm assuming, I have a very basic syntactic error in my script, but I can't put my finger on it

1

There are 1 answers

0
Marco On

Nimizens comment was correct. I somehow tried combinations of $using:$foo or $($using:$foo), not realising, that the second dollar sign was the culprit.

param(
  [int]$iterations = 25,
  [Int32]$throttleLimit = 5,
  [string]$targetUri = "http://localhost:3000/foo"
)

Write-Host "Running $iterations iterations with a throttle limit of $throttleLimit"
Write-Host "Target URI: $targetUri"

1..$iterations | Foreach-Object -ThrottleLimit $throttleLimit -Parallel {
  try {
    $Result = Invoke-WebRequest -Uri $using:targetUri
    $StatusCode = $Result.StatusCode
  }
  catch {
    $StatusCode = $_.Exception.Response.StatusCode.value__
  }
   $StatusCode
}