PowerShell - execute script block in specific scope PowerShell - execute script block in specific scope powershell powershell

PowerShell - execute script block in specific scope


The call operator (&) always uses a new scope. Instead, use the dot source (.) operator:

$ErrorActionPreference = "Stop"function describe()    {    $aaaa = 0;    . before { $aaaa = 2; };    . after { $aaaa; }    }function before( [scriptblock]$sb )    {    . $sb    }function after( $sb )    {    . $sb    }describe

Note the use of . function to invoke the function in same scope as where `$aaaa is defined.