Adding PowerShell Snippets to Visual Studio Code

So I’ve recently moved my daily work to a different laptop, a Yoga 900 with 16GB of RAM to be exact. I had been running Windows 8.1 but decided to jump in completely to a Windows 10 environment. As part of the process I’ve also made it a goal to begin using Visual Studio Code (VS Code) for my PowerShell work. Like many of you I am heavily invested in the PowerShell ISE so I know this won’t be easy. I’ve customized the PowerShell ISE extensively and have a lot of muscle memory that will need to be re-trained. One of the most important elements for me are snippets.

I rely heavily on intellisense and my own snippets to increase my efficiency when working on a script project. Once you get Visual Studio Code installed, along with the PowerShell extension, there is a lot going for you out of the box. Tab completion and intellisense seems to be even more pervasive than in the PowerShell ISE. I suspect many of the snippets I used to rely on are no longer necessary in VS Code.

But I still want to a few so here’s how.

All of the VS Code snippets are stored in language specific json files. In VS Code click on File – Preferences – User Snippets and start typing ‘PowerShell’.

image

Select PowerShell and hit Enter. This will open the default snippets file which is stored in $env:appdata\code\user\snippets\powershell.json.

image

What you see is a comment describing what to insert.  Move your cursor to above the closing curly brace and type the name for your snippet in quotes followed by a colon and open curly brace.

The snippet needs a prefix which will be the text you type to activate the snippet, a body and a description. End each line with a comma.

And end on the next line with a closing curly brace. The finished result should look like this:

image

Use Ctrl+S to save the file. Open a new file (Ctrl+N). By default this will be a plain text file.

image

But if you click on the type you can change it to PowerShell. Now VS Code will apply all PowerShell-related features including the new snippet. Start typing the prefix:

image

Hit Enter and the snippet is inserted.

image

Let’s add another snippet.  After the closing curly brace for the Quote snippet, type a comma and hit enter. Start the snippet on the next line.

I like using this line in my functions.

But if I stick that line into the snippet file you’ll see there is a problem. [Update: I realized I had a mistake in my code which I’ve since fixed, although the screen shots may show the “bad” code]

image

Red text is never good and there is a squiggle under the opening [.  Json files can be tricky. The body value needs to be quoted as a string but I also need the verbose message to be inserted as a string with the double quotes so my variables expand. the trick is to escape those quote marks.

Save the PowerShell.json file, go back to the script and insert the ‘startingps’ snippet.

image

Close — but I didn’t get the $ in front the mycommand variable. In VS Code snippets you can insert placeholders like $1 and $2. In the current state VS Code thinks I’m trying to do that when I really need the literal $. After some trial and error this seems to work.

image

I inserted another $. Now when I save the file and insert the snippet it works as expected.

My snippets so far have been one-liners. But often I (and you ) will want to insert multiple lines. The only thing you need to do differently is insert the body as an object between a set of square brackets, and end each line with a comma.

If you are paying close attention you’ll also see “\t” inserted before Write-Verbose. This will insert a single tab.

image

If you need a blank line use  “\r”.

Sure, it may take a little time to get a snippet set up, but the point is that it is something you will use often and will pay for itself in no time.

As I continue to explore VS Code I’ll share my experiences either here on in the PowerShell section of Petri.com.

16 thoughts on “Adding PowerShell Snippets to Visual Studio Code

  1. I just blogged about snippets but really struggling with the date thing. Just a simple comment based help where I want to include filename and date the file was created. The file name is easy “\tFile Name: $TM_FILENAME”, but getting it to use the datetime variable….

      • Yeah I have gone through that documentation (hence how I found the ability to dynamically add the filename with TM_FILENAME. It seems the question about datetime has been asked a few times and the answer seems to be there is no way. I got spoiled with the Sapien stuff I suppose 🙂 btw there are extensions that make creating snippets easy. My testing however shows you need to be careful which version (Insiders or not) of Code you are running as the Snippet Maker extensions I am testing seem to work but if you are running Insiders version, the snippet is being added to \Roaming\Code\User\Snippets versus \Roaming\Code – Insiders\User\Snippets

    • I found a suggestion on StackOverflow for inserting date and time. Install the “Insert Date String” extension. Then create a snippet like this:

      “Test” : {
      “prefix”: “mysnip”,
      “body”: “# File: $TM_FILEPATH ${date:Insert today’s date (Ctrl+Shift+I)}”,
      “description” : “testing snippet”
      }

      When you insert the snippet the replacement will be selected. Press Ctrl+Shift+I to insert the datetime.

      • That doesn’t seem to add the date when you call the snippet but nice extension to have and I will look to see if maybe I need to call it a different way. Thank you sir. Also looking to use this for adding comments… something like
        .NOTES
        \tMM.dd.yyyy JJK: adding comment to Notes
        and maybe another like:
        \tMM.dd.yyyy JJK: TODO add something to this script/function

      • No it won’t insert the actual date, but the selection will be highlighted so you just need to hit the keyboard shortcut to insert the date.

  2. Have you thought about creating a dynamic snippet creator? Input a here string (like the ISE snippets) and out pops a Piece of json with all the tabs, escapes, and brackets in the right places. I’ve been interested in doing this, just haven’t had the time to spend on it, and lost interest when Keith Hill published his vscode snippets 🙂

  3. I have also used an Extension called Easy Snippet Maker which makes creating snippets very easy, plug in the type of Snippet, Name, Prefix and Description and it will create the snippet for you in the json file. Early in testing but this doesn’t seem to work in Visual Studio Code for Insiders but does work in the in the non-insiders version.

    • I got that extension to work but I had to delete the block comment from the PowerShell.json file. I’m using a standard VS Code build so it works just fine. Great in fact.

  4. Pingback: PowerShell Function Snippet for VSCode | MWJ Computing
  5. In VSCode, if your snippets json file formatting gets unreadable, where everything is essentially one long string, open the file in VSCdoe and use Shift+Alt+F to make it pretty. Then save the file.

  6. Am I crazy, or does this seem like a lot of work to store and get snippets?
    What about using Idera’s “Powershell” Plus tool?

    • There are Visual Studio Code extensions that simplify the whole process. I use Easy Snippet Maker. But I think it helps to know where snippets live and how you can use them. As for PowerShell Plus, last I checked that product hasn’t been updated in ages, not that it won’t work because clearly it still does. There are plenty of other reasons for moving to VS Code other than snippets and if those reasons don’t apply to you there’s no reason to change.

  7. You could also install Easy Snippet Maker extension that lets you create snippets by highlighting the part of the code in the editor

    • Very true and in a followup post I mention that. But even with that it is still helpful to know where and how snippets work.

Comments are closed.