PowerShell ScriptBlock variable scope PowerShell ScriptBlock variable scope powershell powershell

PowerShell ScriptBlock variable scope


You need to explicitly create a closure:

$sb1 = {    Param($Message1);    Write-Host $Message1;    {        Param($Message2);        Write-Host ($Message1 + " " + $Message2);    }.GetNewClosure()}

It then works for me:

PS> $2 = & $sb1 OneOnePS> & $2 TwoOne Two