A sad thing about PowerShell is that function and scriptblocks are dynamically scoped.
But there is another thing that surprised me is that variables behave as a copy-on-write within an inner scope.
$array=@("g")
function foo()
{
$array += "h"
Write-Host $array
}
& {
$array +="s"
Write-Host $array
}
foo
Write-Host $array
The output is:
g s
g h
g
Which makes dynamic scoping a little bit less painful. But how do I avoid the copy-on-write?
You can use scope modifiers or the
*-Variablecmdlets.The scope modifiers are:
globalused to access/modify at the outermost scope (eg. the interactive shell)scriptused on access/modify at the scope of the running script (.ps1file). If not running a script then operates asglobal.(For the
-Scopeparameter of the*-Variablecmdlets see the help.)Eg. in your second example, to directly modify the global
$array:For more details see the help topic about_scopes.