“Tab”容器等同于 ISE 中的运行空间(或powershell 执行环境)。由于您正在创建一个新选项卡(即 powershell 执行环境),因此变量 v 在该执行环境中未定义。脚本块在新的执行环境中进行评估并输出 v 的值(无)。
如果您尝试通过明确提及应该找到变量的范围来获取脚本块中的变量,那么很容易看出在 Test-Scriptblock 的情况下变量分辨率与 Start-NewTab 的情况有何不同。
PS>Test-ScriptBlock { get-variable v -scope 0}
Get-Variable : Cannot find a variable with name 'v'.
PS>Test-ScriptBlock { get-variable v -scope 1}
Get-Variable : Cannot find a variable with name 'v'.
PS>Test-ScriptBlock { get-variable v -scope 2} # Variable found in grandparent scope (global in the same execution environment)
Name Value
---- -----
v hello world
PS>Start-NewTab "Test" { get-variable v -scope 0 } # global scope of new execution environment
Get-Variable : Cannot find a variable with name 'v'.
PS>Start-NewTab "Test" { get-variable v -scope 1 } # proof that scope 0 = global scope
Get-Variable : The scope number '1' exceeds the number of active scopes.
您的问题的一种解决方法是在脚本块中定义您的变量:
Start-NewTab "Test" { $v = "hello world";$v }
编辑:还有一件事,你的标题提到了“关闭”。Powershell 中的脚本块不是闭包,但是您可以从脚本块创建闭包。但是,这不会帮助您解决您描述的问题。
Edit2:另一种解决方法:
$v = "hello world"
Invoke-Expression "`$script = { '$v' }"
Start-NewTab "test" $script