Super Size Your Snippets
Today I want to return to a topic I've covered, at least briefly, in the past and that is taking advantage of snippets in Visual Studio Code. The PowerShell ISE also supports snippets, but since that tool is considered deprecated and is limited to PowerShell, I'm not going to cover that tool today. VS Code is a much more versatile tool and is my preferred editor for PowerShell scripting, writing Markdown documents, working with JSON files, and much more. Each of these tasks requires a different file type and VS Code allows me to create and leverage snippets for each file type. All of this makes me more efficient.
VS Code ships with many built-in snippets for PowerShell, but you can create your own. You can also create snippets for other file types. In this article, I'll show you how to create and use snippets in VS Code.
The Snippet Manager
UPDATE A reader alerted me after I published this that the Snippet Manager is part of the Easy Snippet VS Code extension which I mention later in the article. You will want the extension anyway so you'll need to install it for the rest of this article to make any sense. Sorry for the confusion.
The first thing to do is to open the Snippet Manager. In the left sidebar, also known as the Activity Bar, you can click the snippets icon.
If the Activity Bar is hidden, open the Command Palette with Ctrl+Shift+P
and start typing activity
.
Select Focus Activity Bar
to restore it.
When you click on the snippets icon, you'll open the Snippet Manager.
Click on one the languages to expand it.
Inserting Snippets
In the snippet list, you'll see the snippet name followed by a brief description. I'll move to a PowerShell file and start type ansi
. VSCode will begin to auto-complete the snippet name. I can press Ctrl+Space
to see snippet detail.
Pressing Enter
will insert the snippet.
$([char]27)[
This is a simple example.
Some of the PowerShell snippets have placeholders. I'll insert the If
snippet into my PowerShell script file.
Type your PowerShell code in the selected area.
if (${$x -gt 10 }) {
}
I have to admit I don't like the way some of these snippets are setup with the extra braces. I typically will revised the inserted code.
if ($x -gt 10 ) {
}
You will also encounter snippets like this. I've inserted the for
snippet into my PowerShell script.
You can see the highlighted elements. Notice the placeholder i
is selected and shown three times. I can type x
as my variable and it is changed in all three places.
I can press Tab
to move to the next placeholder and insert a value.
This leaves me with this code in my file.
for (${x} = 0; ${x} -lt ${10}; ${x}++) {
}
Which I'll revise.
for ($x = 0; $x -lt 10; $x++) {
}
I'll revisit placeholders later.
Creating Snippets
While the built-in snippets are handy, I expect you have bits of code you re-use all the time. Turn them into a snippet. I'm going to create a new PowerShell snippet that will insert the ANSI reset sequence.
In the Snippet Manager, click the +
icon next to the appropriate language. Insert the key for your snippet.
This is the value you will type in the VSCode editor to insert the snippet. VSCode will open a new tab where you can define the snippet.
After @description
I recommend adding a brief snippet description. Then you can insert the snippet text. In my example, this is short.
# @prefix ansi-reset
# @description Insert the ANSI reset sequence
$([char]27)[0m
Be careful not to include any more blank lines than you need. Otherwise, all of the blank lines will also be inserted into your file.
When finished, save the snippet with Ctrl+S
. You can close the tab if you are finished.
In my code, I can begin typing ansi
and VS Code should show me the snippet choice.
Pressing Enter
will insert the snippet.
Snippet Variables
I'm going to create another PowerShell snippet, but this type I want to include placeholders. I follow the same steps as before to create a new snippet. I'm calling this mypscustomobject
and it will insert a custom object hash table.
# @prefix mypscustomobject
# @description My PSCustomObject hashtable with PSTypename
[PSCustomObject]@{
PSTypename = "${PSTypeName}"
${PropertyName1} = ''
${PropertyName2} = ''
${PropertyName3} = ''
Computername = [System.Environment]::MachineName
}
The placeholders are enclosed in ${}
. When I insert the snippet, I can press Tab
to move to the next placeholder.
I can type the value for PSTypeName
and press Tab
to move to the next placeholder.
One word of caution, VS Code can sometimes be too helpful. If VSCode completes a value, it will break out of the snippet and you'll have to manually move to the next placeholder.
Let me share one more example. This is a snippet to define a Crescendo parameter.
# @prefix crParameter
# @description Create a Crescendo parameter
\$${paramVariableName} = New-ParameterInfo -Name ${ParameterName} -OriginalName ${OriginalParameterName}
\$${paramVariableName}.OriginalText = "Insert original command help piped to Out-String"
\$${paramVariableName}.Description = "${ParameterDescription}"
\$${paramVariableName}.DefaultValue = "${DefaultValue}"
\$${paramVariableName}.ParameterType = "${ParameterType}"
\$${paramVariableName}.AdditionalParameterAttributes = @('[ValidateNotNullOrEmpty()]')
\$${paramVariableName}.Mandatory = \$False
\$${paramVariableName}.ParameterSetName = "default"
\$${paramVariableName}.Aliases = @()
\$${paramVariableName}.Position = ${Position}
\$${paramVariableName}.OriginalPosition = ${OriginalPosition}
\$${paramVariableName}.ValueFromPipeline = \$False
\$${paramVariableName}.ValueFromPipelineByPropertyName = \$False
In the snippet, I want values like $False
to be inserted with the dollar sign. I am escaping the dollar sign with a backslash. In other places, I want to use placeholders like ${Position}
. Notice the beginning of each line: \$${paramVariableName}
. When I insert the snippet, I want to be able to keep the dollar sign and replace the ${paramVariableName}
placeholder.
I can type a value for paramVariableName
and the value for paramVariableName
is inserted throughout the snippet. I can then press Tab
to move to the next placeholder and in very short order have a complete Crescendo parameter definition!
There's no limit to what you can insert into a snippet file, except evaluated code. You can't create a snippet that runs code and inserts the result.
Synchronizing
If you are synchronizing your VSCode settings between computers, and if you have multiple computers you should be, you can synchronize your snippets. To verify, open the synchronization settings.
In the configuration, you can verify what settings to synchronize.
Make sure you check Extensions
.
Backup
You also might want to verify you are backing up your snippet settings. Each group is stored as a JSON file under APPDATA
.
PS C:\> cd $env:APPDATA\code\user\snippets
PS C:\Users\Jeff\AppData\Roaming\Code\User\snippets> dir
Directory: C:\Users\Jeff\AppData\Roaming\Code\User\snippets
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 12/3/2024 10:18 AM 390 json.json
-a--- 12/3/2024 10:23 AM 3498 markdown.json
-a--- 2/23/2023 5:37 PM 11773 plaintext.json
-a--- 12/3/2024 1:14 PM 33259 powershell.json
-a--- 2/23/2023 5:37 PM 111 undefined.json
-a--- 2/23/2023 5:37 PM 234 xml.json
You can use whatever process you want to backup or manually synchronize these files
VSCode Extensions
The VSCode eco system has many extensions related to snippets. Type snippets
in the Extensions search bar to see what is available.
One extension I use to accelerate creating my own snippets is Easy Snippet
which let's me take a selection of code or text and turn it into a snippet.
Summary
You can also list available snippets for a given file type by pressing Ctrl+Space
without typing anything. Scroll to the snippet you want and press Enter
. If you aren't taking advantage of snippets you are working too hard. It make take a few minutes to create the snippet, but it will save you a lot of work in the long run. I'd love to hear how you are using snippets in your work.
An alert reader informed me that the Snippet Manager is apparently part of the Easy Snippet VSCode extension. I've added a comment to the article.