[powershell] Variable scoping in PowerShell

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?

This question is related to powershell scope

The answer is