Fun with ISE – Snippets

In Powershell ISE there’s a nice feature…
Press Ctrl-J and you will get a list of snippets that you can use

snippets_list

So what is a snippet?
Well, the easiest way to describe them is that they are templates of different things, like if you choose the one called “Cmdlet (advanced funtion)” You will get this in your code window

<#
.Synopsis
   Short description
.DESCRIPTION
   Long description
.EXAMPLE
   Example of how to use this cmdlet
.EXAMPLE
   Another example of how to use this cmdlet
#>
function Verb-Noun
{
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
        # Param1 help description
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        $Param1,

        # Param2 help description
        [int]
        $Param2
    )
    
    Begin
    {
    }
    Process
    {
    }
    End
    {
    }
}

A good place to start when you’re going to create acmdlet or function.

Or if you never can remember how to use the switch selection, just choose that snippet and you will get an example

switch ($x)
{
    'value1' {}
    {$_ -in 'A','B','C'} {}
    'value3' {}
    Default {}
}

Another cool thing is that you can create your own snippets!
The easiest way to create one is to write your code in a new tab and after you’re done with it, you encapsule everything within ‘ and add it to a variable, like this:

$snippet = '###################################
# Name        : 
# Description : 
# Author      :
# Created     :
# Updated     :
###################################'

Then run it with F5 so that it get’s stored in the variable, next is to create the snippet

New-IseSnippet -Description "Header Block" -Text $snippet -Title "0 Header"

Why I have the 0 first in the title is because I want it at the top of the list when I press Ctrl-J :)

new_snippet_list

And When I’ve selected it, it looks like this

header

Have fun with your snippets :)

Leave a Reply

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