0

powersell variable scope include:global,script,private,local.

I test a variable in loop, bug why it have value outside loop?

$a=$false
for ($i = 0; $i -lt 10; $i++) {
    $private:recObj=@{}
    $private:recObj.id=$i
    if ($i -lt 6) {
        $a=$true
    }else {
        $a=$false
    }

    $private:recObj.a=$a
    $private:recObj.b="2323"
}

$private:recObj #recObj is private, why here have output? I want it is null

the result:

Name                           Value
----                           -----
b                              2323
id                             9
a                              False

2 Answers 2

4

Loop bodies in PowerShell are not scopes. Private in this case is the entire script.

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

Comments

0

I am not an expert in this, but I want to highlight few things.

Scopes are like our Dot Net Scopes:

  • Global is public,

  • Script is internal,

  • Private is private,

  • Local is current stack level

Next one is the Visiblity

By default powershell visiblity is Public.

if you use

(Get-Variable -Name recObj).Visibility

you should see the visibility of that variable. If you consider the for loops as a separate scope, then its wrong in PS.

Third, you do not need to declare everywhere private; one time will do that:

$a=$false
for ($i = 0; $i -lt 10; $i++) {
    $private:recObj=@{}
    $recObj.id=$i
    if ($i -lt 6) {
        $a=$true
    }else {
        $a=$false
    }

    $recObj.a=$a
    $recObj.b="2323"
}
$recObj

But you want to restrict it , then you explicitly make the visibility private.

 Set-Variable recObj -Visibility Private

Hope it helps you in better understanding.

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.