Toggling Comments in PowerShell ISE

by Nov 28, 2017

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("#>") 
    }
    else
    {                            
        $comment = "<#" + $text + "#>"    
    }
    $file.Editor.InsertText($comment)                     
}

$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!