PowerShell ISE 如何使用 ScriptBlock 关闭自动创建新选项卡?

标签 powershell powershell-2.0 powershell-ise

我正在尝试在 PowerShell ISE 中自动创建一堆选项卡

我已经开始使用一个函数,例如

function Start-NewTab($name, [ScriptBlock]$scriptBlock)
{
    $tab = $psISE.PowerShellTabs.Add()
    $tab.DisplayName = $name
    sleep 2
    $tab.Invoke($scriptBlock)
}

但是当我像这样运行它时
$v = "hello world"
Start-NewTab "Test" { $v }
hello world未显示,与以下片段不同
function Test-ScriptBlock([ScriptBlock]$sb) { & $sb }
Test-ScriptBlock { $v }

这里发生了什么,我该如何解决?

最佳答案

“Tab”容器等同于 ISE 中的运行空间(或 powershell execution environment)。由于您正在创建一个新选项卡(即 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 中的脚本块不是闭包,但是您可以从脚本块创建闭包。但是,这不会帮助您解决您描述的问题。

编辑 2:另一种解决方法:
$v = "hello world"
Invoke-Expression "`$script = { '$v' }"
Start-NewTab "test" $script

关于PowerShell ISE 如何使用 ScriptBlock 关闭自动创建新选项卡?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9162295/

相关文章:

rest - 更新Azure DevOps Wiki页面使用Powershell

Powershell 将日期更改为 dd/mm/yyyy hh :ss format and then to string

parsing - 从变量而不是文件导入CSV?

sharepoint - 使用 powershell 将文件上传到 SharePoint 文档库

powershell - 将文件列表复制到目录

Powershell ISE 在(愚蠢地)删除所有变量后无法启动

windows - Powershell 锁定第一个和最后一个文件,如果不关闭 powershell ISE,我无法删除它们

powershell - 下载 Powershell 文档

xml - XPath 查询精确匹配

powershell - 将路径管道传递到测试路径时,PowerShell ISE “Illegal characters in path”?