Grouping your Snippets in PowerShell ISE

One way of grouping your snippets in PowerShell ISE is to create a custom Add-On menu item. The example below demonstrates a function that groups your snippets based on the author (company) who wrote it. If the author property is empty, the snippets will be placed under a “unknown” submenu.

Clicking on Add-Ons/Grouped Snippets gives you the view shown above.

If you click on a specific Snippet, the Snippet code will be placed in your current file.

The following function is used to display a custom “Grouped Snippets” Menu Item.

 

function Group-TSSnippet {
  $menuText = "Grouped Snippets"
  $psISE.PowerShellTabs | ForEach-Object {
    $psTab = $_
    [array]$psTab.AddOnsMenu.Submenus |
     Where-Object {$_.DisplayName -eq $menuText} |
      ForEach-Object {
       $psTab.AddOnsMenu.Submenus.Remove($_) | Out-Null
      }

    $menu = $pstab.AddOnsMenu.Submenus.Add($menuText, $null, $null)
    $psTab.Snippets |
     Group-Object Author | Select Name |
      ForEach-Object {
      if([string]::IsNullOrEmpty($_.Name)) {
        $name = "Unknown"
      } else {
        $name = $_.Name
      }
      $menu.Submenus.Add($name,$null,$null) | Out-Null
    }
    foreach($snippet in $psTab.Snippets) {
      if([string]::IsNullOrEmpty($snippet.Author)) {
        $name = "Unknown"
      } else {
        $name = $snippet.Author
      }
      # Get Snippy Group
      $subMenu = $menu.Submenus | Where-Object { $_.DisplayName -eq $name }
      $codeFragment = "`n@'`n" + $snippet.CodeFragment + "`n'@`n"
      $action = '$psise.CurrentFile.Editor.InsertText(' +  $codeFragment + ')'
      $subMenu.Submenus.Add(
        $snippet.DisplayTitle,[scriptblock]::Create($action), $null
      ) | Out-Null
    }
  }
}

 

You can run the function by simply typing:

 

 PS > Group-TSSnippet 

 

Click here to download the function

Rating 4.00 out of 5
[?]

One thought on “Grouping your Snippets in PowerShell ISE

  1. Hey, I haven’t tested the upcoming Poershell yet. Are snippets a new feature of the ISEv3?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Anti-Spam Protection by WP-SpamFree