PowerShell-在特定范围内执行脚本 block

标签 powershell scope

我正在尝试在Powershell中实现RSpec/Jasmine之类的BDD框架(或至少研究制造它的潜在问题)。

目前,我在实现简单的之前/之后功能方面遇到问题。给定

$ErrorActionPreference = "Stop"

function describe()
    {
    $aaaa = 0;
    before { $aaaa = 2; };
    after { $aaaa; }
    }

function before( [scriptblock]$sb )
    {
    & $sb
    }

function after( $sb )
    {
    & $sb
    }

describe

输出为0,但我希望它为2。在Powershell中有什么方法可以实现它(除了使$ aaaa成为全局对象,在脚本块中遍历父作用域,直到找到$ aaaa,使$ aaaa成为“对象”和其他肮脏的黑客:))

我理想的情况是希望在其他范围内调用脚本块,但是我完全不知道是否有可能。我在https://connect.microsoft.com/PowerShell/feedback/details/560504/scriptblock-gets-incorrect-parent-scope-in-module上找到了一个有趣的示例(请参阅解决方法),但不确定其工作方式以及是否以任何方式对我有帮助。

TIA

最佳答案

调用运算符(&)始终使用新范围。而是使用点源(.)运算符:

$ErrorActionPreference = "Stop"

function describe()
    {
    $aaaa = 0;
    . before { $aaaa = 2; };
    . after { $aaaa; }
    }

function before( [scriptblock]$sb )
    {
    . $sb
    }

function after( $sb )
    {
    . $sb
    }

describe

注意,在定义$ aaaa的相同作用域内,使用. function调用该函数。

关于PowerShell-在特定范围内执行脚本 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11707590/

相关文章:

angularjs - 在 AngularJS 中,当使用 "controller as"语法和 "this"时,如何在 promise 的回调中引用 "this"?

javascript - 在 AngularJS 中将作用域的值传递给另一个作用域

javascript - 冒泡范围 - 从嵌套函数更新 var

javascript - 将指向对象方法的指针安全地传递给 google.maps.event.addListener

powershell - Azure Powershell : Restoring a blob snapshot to a different VM

powershell - "get-wmiobject win32_process -computername"得到错误 "Access denied , code 0x80070005"

powershell - 使用PowerShell从zip文件提取目录的最优雅方法?

xml - Powershell xpath-获取两个属性的值

引用的 C++ 变量范围

powershell - 在Powershell模块功能中发出错误的正确方法是什么?