Visual Studio Code Snippets and PowerShell

You often repeat certain standard things when writing scripts in Visual Studio Code. Wouldn’t it be nice if we could simplify that? This blog post will show you how to use VSCode Snippets to your advantage!

What are Snippets?

“Code snippets are templates that make it easier to enter repeating code patterns, such as loops or conditional-statements.”

How do I use them?

Well… You are probably already using them. IntelliSense automatically starts using them when you type in a specific command part and press Tab. For example, when typing “Fore” the IntelliSense already suggests the Foreach cmdlet:

When you press Tab, it will expand to this giving you a pre-defined template that you can use and will save you time typing 🙂

Creating your Snippets

If you have certain things you want to use often without having to copy/paste it from previous scripts, you can add your snippets. The steps for adding one are as follows:

  • Start VSCode
  • Select File, Preferences, Configure User Snippets, and select powershell.json
  • In the editor window of powershell.json, you will see an example:
{
	// Place your snippets for powershell here. Each snippet is defined under a snippet name and has a prefix, body and 
	// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
	// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the 
	// same ids are connected.
	// Example:
	// "Print to console": {
	// 	"prefix": "log",
	// 	"body": [
	// 		"console.log('$1');",
	// 		"$2"
	// 	],
	// 	"description": "Log output to console"
	// }
}

You can add your one between the outer brackets. For instance, I added one here for a simple custom object loop that I use often:

	"Total customobject loop": {
	"prefix": "Total",
	"body": [
		"$$total = Foreach ($$variable in $$collection) {",
		"\t[pscustomobject]@{",
			"\t\t Name = $$variable.Name",
		"\t}",
		"}",
		"$$total | Export-CSV -Path c:\\temp\\total.csv -NoTypeInformation -Encoding UTF8 -Delimiter ';'"
	],
	"description": "Create a $total loop with a customobject inside"
	}

Note that the syntax is somewhat different in the body. You must escape characters like the $-sign and the back-slash with an additional $ or \. The \t is a Tab sign for indenting the code. The powershell.json file looks like this after adding the above Snippet: (You can leave the top part as an example in the powershell.json file)

{
	// Place your snippets for powershell here. Each snippet is defined under a snippet name and has a prefix, body and 
	// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
	// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the 
	// same ids are connected.
	// Example:
	// "Print to console": {
	// 	"prefix": "log",
	// 	"body": [
	// 		"console.log('$1');",
	// 		"$2"
	// 	],
	// 	"description": "Log output to console"
	// }

	"Total customobject loop": {
	"prefix": "Total",
	"body": [
		"$$total = Foreach ($$variable in $$collection) {",
		"\t[pscustomobject]@{",
			"\t\t Name = $$variable.Name",
		"\t}",
		"}",
		"$$total | Export-CSV -Path c:\\temp\\total.csv -NoTypeInformation -Encoding UTF8 -Delimiter ';'"
	],
	"description": "Create a $total loop with a customobject inside"
	}
}

Using your Snippet in VSCode

Now that we have created an example VSCode Snippet, you can use it by typing “total”, and it should appear in the list:

By pressing Tab, it should insert it for you:

Now you only have to add/replace certain things, but it saves time! You will also have more consistent code because of the Snippet, which is always good 🙂

7 thoughts on “Visual Studio Code Snippets and PowerShell

  1. Snippets are great so thanks for posting this. You can also make them interactive like a piece for my Comment Based Help:
    “.NOTES\r”,
    “\t===========================================================================\r”,
    “\tCreated with:\tVisual Studio Code\r”,
    “\tCreated on:\t\t$CURRENT_YEAR-$CURRENT_MONTH-$CURRENT_DATE $CURRENT_HOUR:$CURRENT_MINUTE:$CURRENT_SECOND\r”,
    “\tCreated by:\t\tAuthor/Developer Name\r”,
    “\tOrganization:\tMednax\r”,
    “\tFilename:\t\t$TM_FILENAME\r”,
    “\t===========================================================================\r”,
    So the snippet will auto fill the Created On and filename and maybe some drop-down lists
    “[parameter(Mandatory=$${1|True,False|}, ValueFromPipeline=${2|$True,$False|},\r”

  2. Pingback: Intune Newsletter - 24th February 2023 - Andrew Taylor

Leave a Reply to danCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.