【问题标题】:PowerShell ISE Profile loading scripts in tabsPowerShell ISE 配置文件在选项卡中加载脚本
【发布时间】:2020-09-08 20:33:01
【问题描述】:

我想向 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

【问题讨论】:

  • 仅有条件地运行代码 sn -p if ( $psISE.PowerShellTabs.Count -le 1) {}?
  • 这可能会解决死循环。但我需要创建几个选项卡,在创建下一个等之前在新打开的选项卡中打开几个脚本。

标签: powershell powershell-ise


【解决方案1】:

它使用当前代码无休止地打开新标签的原因是每个新标签都会设置自己的运行空间并(再次)加载配置文件

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

# 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
    }
}

【讨论】:

  • 太棒了!这解决了很多令人头疼的问题,希望它也能让其他系统管理员的工作更轻松。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多