arealhobo
arealhobo

Reputation: 467

Powershell - Setting a variable inside a function not setting it globally?

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?

Upvotes: 1

Views: 1125

Answers (3)

jfrmilner
jfrmilner

Reputation: 1778

$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.

Upvotes: 3

Tobias Meyer
Tobias Meyer

Reputation: 71

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

Upvotes: 0

Svyatoslav Pidgorny
Svyatoslav Pidgorny

Reputation: 643

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

Upvotes: 2

Related Questions