Add PowerShell Snippets to Visual Studio Code

Visual Studio Code Logo

Add PowerShell Snippets to Visual Studio Code

Visual Studio Code Logo

Intro

Visual Studio Code Snippets are stored in JSON files, one JSON file for each language PowerShell, Python, rust etc. In this write up we will be adding a new custom snippet ForEachWithProgress.

Prefix = what you need to type in VS Code in order for the snippet suggestion to pop up
powershell.json is located in the following locations

Linux

~/.config/Code/User/snippets/powershell.json

Windows

$env:appdata\code\user\snippets\powershell.json

Edit powershell.json

You will add in a new JSON block “My New Snippet”: { } withing the already existing {}
You will need to
escape ” with a \
escape $ with a $$

"ForEachWithProgress": {
		"prefix": "foreach",
		"description": "foreach with write progress",
		"body": [
			"$$CounterCollection = 0",
			"foreach ($$item in $$Collection)",
			"\t{",
			"\t\tWrite-Progress -Status 'Comparing' -Activity \"$CounterCollection of $($Collection.Count) Iterating Over Collecction\" -PercentComplete $($CounterCollection / $($Collection.Count) * 100)",
			"\t\t$$CounterCollection++",
			"\t}",
		]
	}

Then use something like Ansible to push it out across the fleet

  • https://code.visualstudio.com/docs/editor/userdefinedsnippets
  • https://code.visualstudio.com/