选项卡中的PowerShell ISE配置文件加载脚本

问题描述

我想向PowerShell ISE配置文件(Microsoft.PowerShellISE_profile.ps1)添加一个部分,该部分执行以下操作:

  1. 使用给定名称创建几个新标签
  2. 在每个标签内打开一个或多个唯一的脚本文件(不运行脚本,只需打开文件

我曾考虑做类似下面的代码片段之类的事情,但是在打开ISE时它会创建无尽的新标签,而我可以按照自己的意愿去做。

$tab1 = $psISE.PowerShellTabs.Add()
$tab1.displayName = "First-tab"

While (-not $tab1.CanInvoke) {
    Start-Sleep -m 100
}

所需堆积物的示例:

  1. 首选项卡
    • 脚本1
    • 脚本2
  2. 第二个标签
    • 脚本3
  3. 第三标签
    • 脚本4
    • 脚本5

解决方法

用当前代码无休止地打开新选项卡的原因是每个新选项卡都会设置自己的运行空间并再次加载配置文件。

一种方法是让配置文件脚本的每次执行负责加载自己的脚本,打开下一个脚本(如果有),然后返回:

# Define tabs and their content
$Tabs = [ordered]@{
    'Tab One' = @(
        '.\path\to\Script1.ps1'
        '.\path\to\Script2.ps1'
    )
    'Tab Two' = @(
        '.\path\to\Script3.ps1'
    )
    'Tab Three' = @(
        '.\path\to\Script4.ps1'
    )
}

foreach($tabDef in $Tabs.GetEnumerator()){
    # Loop through the tab definitions until we reach one that hasn't been configured yet
    if(-not $psISE.PowerShellTabs.Where({$_.DisplayName -eq $tabDef.Name})){

        # Set the name of the tab that was just created
        $psISE.CurrentPowerShellTab.DisplayName = $tabDef.Name

        # Open the corresponding files
        foreach($file in Get-Item -Path $tabDef.Value){
            $psISE.CurrentPowerShellTab.Files.Add($file.FullName)
        }

        if($psISE.PowerShellTabs.Count -lt $Tabs.Count){
            # Still tabs to be opened
            $newTab = $psISE.PowerShellTabs.Add()        
        }

        # Nothing more to be done - if we just opened a new tab it will take care of itself
        return
    }
}