1

I have the following code:

$firstRun = 'True'

$file | ForEach-Object {

    Function Do-Stuff {
        if ($firstRun = 'True') {

            write-host "null"
            $firstRun = 'False'
        }
    }
Do-Stuff
}

When I call Function 'Do-Stuff', it will run the first time, no matter where I place $firstRun = 'False', it returns true and intiates the if block again. What am I doing wrong?

2
  • check out the docs on variable scope. i suspect that is where your glitch is occurring ... Commented Jan 20, 2020 at 23:50
  • 1
    kool! [grin] it looks like your problem is related to scope. ///// purely as an aside ... i would replace all your tests for the string true with tests for the boolean $True. it makes no difference in your code, but fits better with how PoSh handles False/True. Commented Jan 21, 2020 at 0:35

3 Answers 3

3

$firstRun = 'True' is setting $firstRun to the String 'True'. If you want to see if it equals that value the comparison operator is -eq, so $firstRun -eq 'True'

For more information on comparison operators run Get-Help about_comparison_operators


Thanks for letting us know about the typo, I'll stick with your example to show how you can prefix your variables with global: so you get the required variable scope.

$firstRun = 'True'
Function Do-Stuff {
    if ($global:firstRun  -eq 'True') {

        Write-Host "True"
        $global:firstRun  = 'False'
    }
    else {
        Write-Host "False"
    }
}

$file | ForEach-Object { Do-Stuff }

For more information on scopes check Get-Help about_scopes.

Sign up to request clarification or add additional context in comments.

2 Comments

Shoot, that actually a typo in my sample code. Its not like that in my actual code....
Adding $global:fixed the issue I was having
2

Use $global:firstRun instead of the $firstRun inside the function to reference variable in the global scope.

Comments

0

Your function doesn't return something.

Here is an example with a returning value.

$value1 = 3
$value2 = 5
function Calculate-Something ($number1,$number2)
{
   $result = $number1 + $number2
   return $result
}
$value3 = Calculate-Something -number1 $value1 -number2 $value2
Write-Host $value3

This code sample would add up value1 and value2 and would write the result:

8

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.