0

I know the differences calling variable $var vs $script:var inside of a function. Like this:

function test()
{
    $var = 1
    $script:var = 2
}

test

if ($script:var -eq $var)
{
    Write-Host "$var = $script:var"
}

But I have to write everywhere $script:var not to make mistakes? Is there another good way to achieve the same result? Thank you!

  • No, you do not have to do that at all. Your entire question can be answered by reading the Powershell doc on 'Scope' for functions, variables, etc.... Don't guess at it. – postanote Mar 11 at 5:43
0

No, you do not have to do that at all.

In over a decade of working with PowerShell, It's not something I've ever really needed. Yet, everyone's use case is different. Yet, based on what you are showing, your statement is not generally correct. I cannot think of a daily use case(s) that this would be needed.

Your entire question can be answered by reading the Powershell doc on 'Scope' for functions, variables, etc....

About_Scope

...and this well-done article.

How Scopes Affect PowerShell Scripts

If you want to operate outside of your current scope you should define it with the prefix. Functions should be black box, Set input/output.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.