Using Code Snippets in PowerShell ISE v3

by Aug 9, 2012

PowerShell ISE v3 script editor supports code snippets. Press CTRL+J to open a list of built-in snippets.

You can add your own snippets, too. For example, to easily add error handlers to your scripts, here is a new code snippet:

$code = @'
$ErrorActionPreference = 'Stop'

    $global:g = $_
    $script = $_.InvocationInfo.ScriptName
    $line = $_.InvocationInfo.ScriptLineNumber
    $message = $_.Exception.Message

    Write-Warning ('LINE {0:000} "{1}" Error: {2}' -f $line, $script, $message)



New-IseSnippet -Title 'Trap' -Text $code -Description 'Inserts a global error handler' 
-CaretOffset $code.Length -Force

Note how New-ISESnippet cmdlet sets the caret position to the length of the code snippet text. By default, after you insert a snippet, the cursor is positioned right before the snippet. If you'd rather want to position the cursor at the end of the code snippet, use the approach showed in this sample.

The snippet name is determined by the parameter -Title. To insert the error handler code, simply press CTRL+J and then type the snippet name, for example "trap". Then press ENTER.

New-ISESnippet actually produces snippet files, so the snippets you define do persist. Close PowerShell ISE and reopen it again. Then press CTRL+J. Your custom snippets are still available. Use the parameter -Force to overwrite and replace existing snippets.

Twitter This Tip! ReTweet this Tip!