Grabbing variable from inside a function

Hi there !

I was hoping someone could enlighten me, as to how i can grab information from inside a function (that runs inside a foreach loop several times).

The script works as intended, the only somewhat unimportant, but quite annoying detail is that i cant figure out how to grab the variable $retryCount (which comes from the Function) and print it out with the other result.
I just want to know, in the final output file, how many retries there have been, for each attempt.

If the script fails on $framworkcommand1, it throws the loop, stopping the script from attempting the other commands, which is fine. Im not trying to collect “amount of retries” for every $framworkcommand(1-4).

I would asume, that my correction:
return $response, $retryCount

From originally just:
return $response

Would allow me to grab the variable.
It does not :frowning:

please help! ^^

Link to Github Gist with the script:

Best regards
Jonatan

The variable only exists within the scope of the function, to access it outside of the function you would need to declare it in the Script scope:

Line 17:

$Script:retryCount = 0

Alternatively, you can return it as you have done, but you would need to access it using its position in the returned array.

So when you do this:

$frameworkcommand1 = Req -Params @{ 'Method' = 'GET'; 'Uri' = $url1 }

This would give you the retry count:

$framework[1]
2 Likes

Hi Matt!

Thanks alot for your response :slight_smile:

I declared it in the function like you suggested: $Script:retryCount

Then also replaced the sections in PSCustomObject and Catch (With the same), which now gives me the amount of times tried!

Problem solved, 1000 thanks!

1 Like