简体   繁体   中英

PowerShell ISE Profile loading scripts in tabs

I want to add a section to the PowerShell ISE profile (Microsoft.PowerShellISE_profile.ps1) which does the following:

  1. Creates several new tabs with given names
  2. Inside each of the tabs open one or more unique script files (not running the scripts, just open the files)

I thought about doing something like the code snipet like under, but it creates endlessly new tabs when opening ISE and I to get it to do as I want to have it.

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

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

Example of the desired buildup:

  1. First-tab
    • Script 1
    • Script 2
  2. Second-tab
    • Script 3
  3. Third-tab
    • Script 4
    • Script 5

The reason it endlessly opens new tabs with your current code is that every new tab sets up its own runspace and loads the profile (again) .

One approach is to let each execution of the profile script be responsible for loading its own scripts, open the next (if any), and then return:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM