The good old PowerShell ISE exposes some expandability connectors. If you’d like to toggle comments in selected text by pressing CTRL+K, for example, try this code:

function Toggle-Comment
    $file = $psise.CurrentFile                              
    $text = $file.Editor.SelectedText   
    if ($text.StartsWith("<#")) {
        $comment = $text.Substring(3).TrimEnd("#>") 
        $comment = "<#" + $text + "#>"    

$psise.CurrentPowerShellTab.AddOnsMenu.Submenus.Add('Toggle Comment', { Toggle-Comment }, 'CTRL+K')

It basically uses $psise to access the ISE object model, and then installs a new menu command with keyboard shortcut CTRL+K that invokes Toggle-Comment.

Add this code to your profile script in $profile (file may not yet exist) to run this code every time PowerShell ISE launches.

Twitter This Tip! ReTweet this Tip!

  • There is / was a legacy PowerShell Addon pack that provided this and more. ConvertTo-BlockComment - Comments out selected text with <# before and #> after ConvertTo-BlockUncomment - Removes <# before and #> after selected text ConvertTo-Comment - Comments out selected text with a leading # on every line ConvertTo-Uncomment - Removes leading # on every line of selected text And of easily extendable to other items. Such as I added... ConvertTo-RegionBlock ConvertTo-RegionUnblock ConvertTo-UrlBlock ConvertTo-UrlUnblock and more... and still using that regularly. The $psISE object model provide a plethora of flexibility to do things to enhance you ISE experience.
  • Substring(3) should be replaced by Substring(2) in the function otherwise when uncommenting it will trim first alphabet of the $Text value.