A few days ago I posted an entry that explained how to create and use snippets in Visual Studio Code. As mentioned in that article I'm attempting to make the transition to VSCode for all my PowerShell work. Being able to use snippets is just one feature that I rely on. And as a number of people pointed out, there are VSCode extensions that will make this easy to do. Install the Easy Snippet Maker extension and you'll get a context menu to turn any selected text into a snippet.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
Follow the prompts and if creating a PowerShell snippet it will be added to the PowerShell.json file I showed previously. But there's more you can do with snippets, even after you've created them. This is fun.
I created a function outline:
Function Name { [cmdletbinding()] Param( [Parameter(ValueFromPipeline)] [objecttype]$Variable ) Begin { Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Starting $($myinvocation.mycommand)" } #begin Process { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] $Variable " } #process End { Write-Verbose "[$((Get-Date).TimeofDay) END ] Ending $($myinvocation.mycommand)" } #end } #close Name
And turned it into a VSCode snippet. Because of the variables, which I want inserted, I need to edit the snippet. I found a better way to escape the $ sign for $myinvocation is to use \\$myinvocation. As I wrote previously this is because VSCode allows you use to placeholders in your snippets. This is the fun part. Here's the modified snippet code.
"jh function": { "prefix": "myfunction", "body": [ "Function ${Name} {\r", " [cmdletbinding()]\r", " Param(\r", " [Parameter(ValueFromPipeline)]\r", " [${objecttype}]$${Variable}\r", " )\r", " Begin {\r", " Write-Verbose \"[$((Get-Date).TimeofDay) BEGIN ] Starting $(\\$myinvocation.mycommand)\"\r", "\r", " } #begin\r", "\r", " Process {\r", " Write-Verbose \"[$((Get-Date).TimeofDay) PROCESS] $${Variable} \"\r", "\r", " } #process\r", "\r", " End {\r", " Write-Verbose \"[$((Get-Date).TimeofDay) END ] Ending $(\\$myinvocation.mycommand)\"\r", "\r", " } #end \r", "\r", "} #close ${Name}" ], "description": "My function outline" }
I created place holders like ${Name} and ${ObjectType}. You should also note that I'm using ${Name} several places in the snippet. This is way.
After I insert the snippet, I can tab through the placeholders and start typing replacement text. If there are multiple instances of the placeholder they are all changed at once!
And if your PowerShell.json file formatting gets a bit wonky, such as everything bunched together as one long string, open the file in VSCode and press Alt+Shift+F to make it pretty.
You might also want to take a look at this series of articles from PowerShell MVP Keith Hill https://rkeithhill.wordpress.com/2017/02/19/scripting-guys-blog-posts-on-using-visual-studio-code-for-powershell-development/ to get even more out of VSCode.