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.