0

I'm learning Powershell and I just found a behavior that seems strange coming from a C# background: it seems that a function can access the variables that are defined outside of it! The opposite is not true, a variable defined inside a function is not accessible from the outside.

For example, this script:

function Helper() {
  Write-Host "I can see a variable $outerScopeVariable"
  $innerScopeVariable = "defined in the inner scope"
}

$outerScopeVariable = "defined in the outer scope"
Helper
Write-Host "I can't see a variable $innerScopeVariable"

Will print:

I can see a variable defined in the outer scope
I can't see a variable

So my questions are:

  • Is this the recommended behavior? Is there some option that would block it?
  • Should I use this or should I explicitly pass the variable as a function argument?

Any documentation about this would be appreciated, I've not been able to find anything so far.

Tao Gómez Gil
  • 2,228
  • 20
  • 36
  • 1
    See [about scopes](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_scopes) – iRon Oct 19 '22 at 09:35
  • 1
    "*Should I use this or should I explicitly pass the variable as a function argument?*", you might also used the `function` - or `global` scope identifier `$Global:innerScopeVariable = "defined in the global scope"` but this completely depends on your situation and is **opinion-based** – iRon Oct 19 '22 at 09:42

0 Answers0