PowerShell - 在特定范围内执行脚本块 [英] PowerShell - execute script block in specific scope
问题描述
我正在尝试在 Powershell 中实现 RSpec/Jasmine 之类的 BDD 框架(或者至少研究制作一个的潜在问题).
I am trying to implement RSpec/Jasmine like BDD framework in Powershell (or at least research the potential problems with making one).
目前我在实现简单的前/后功能时遇到问题.给定
Currently I am having problems with implementing simple before/after functionality. Given
$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 成为对象"和其他肮脏的黑客:) )
the output is 0, but I would like it to be 2. Is there any way to achieve it in Powershell (short of making $aaaa global, traversing parent scopes in script blocks till $aaaa is found, making $aaaa an "object" and other dirty hacks:) )
我最想要的是一种在其他范围内调用脚本块的方法,但我根本不知道这是否可行.我在 https 上发现了一个有趣的例子://connect.microsoft.com/PowerShell/feedback/details/560504/scriptblock-gets-incorrect-parent-scope-in-module(请参阅解决方法),但不确定它是如何工作的以及是否有帮助我以任何方式.
What I would ideally like is a way to invoke a script block in some other scope but I don't have a clue whether it is possible at all. I found an interesting example at https://connect.microsoft.com/PowerShell/feedback/details/560504/scriptblock-gets-incorrect-parent-scope-in-module (see workaround), but am not sure how it works and if it helps me in any way.
TIA
推荐答案
调用运算符 (&) 始终使用新的作用域.相反,使用点源 (.) 运算符:
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
注意的使用.function
调用与定义`$aaaa 的作用域相同的函数.
Note the use of . function
to invoke the function in same scope as where `$aaaa is defined.
这篇关于PowerShell - 在特定范围内执行脚本块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!