Add code snippets to Powershell ISE

I have been looking for a user-friendly way to add code snippets to Powershell ISE to reduce typos and time spent copy/pasting.  Borrowing a page from Jeffery Hicks' blog, I took it a step further and used multi-line comments to add large code snippets to the ISE for creating new scripts.  As an example, I often write scripts that take advantage of the Quest ActiveRoles AD Management snapin.  The code below allows me to use ALT + F5 as a hotkey to insert this code into the ISE quickly and easily.

 $QADTools = @'
  function Add-QADTools
  $Quest = Get-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction silentlycontinue
  if ($Quest)
       Write-Debug "Quest.ActiveRoles.ADManagement Snapin loaded"
  if (!$Quest)
       Write-Debug "Loading Quest.ActiveRoles.ADManagement Snapin"
       Add-PSSnapin Quest.ActiveRoles.ADManagement
       if (!$?) {"Need to install AD Snapin from";exit}

  $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Insert QAD Tools", `
{$psise.CurrentFile.Editor.InsertText($QADTools)},"ALT+F5") | out-Null

To implement this into the ISE, you will need to modify/create your Powershell ISE profile.  To find your user profile, you will need to browse to C:\Users\%USERNAME%\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1 and paste the above code into the .ps1 file.  This code will also add a new menu item to the Powershell ISE named 'Add-ons' with a menu item named 'Insert QAD Tools' as shown below.

1 comment: