Does this site look plain?

This site uses advanced css techniques

Those who create PowerShell cmdlets—who I assume are using Visual Studio— surely find themselves typing the same set of code every time the make a new .cs source file to hold a new cmdlet, and I tired of this as well, so finally (after years!) got around to creating a proper new-item template for Visual Studio.

Whoa - SO NICE.

This ended up being far easier than I expected so am documenting it here; I wish I'd have done this a long time ago.

These instructions work for Visual Studio 2017 but believe they apply more widely.

Templates are provided as a ZIP file—such as PowerShell— and are dropped into the $env:USERPROFILE\Visual Studio 2017\Templates\ItemTemplates\ directory.

XML that describes the item that shows up your new-item dialog, points to the .cs file mentioned next, and describes other dependencies for the item.
<VSTemplate Version="3.0.0" xmlns="" Type="Item">
    <DefaultName> My_Cmdlet.cs </DefaultName>
    <Name> My Powershell Cmdlet </Name>
    <Description> Steve's PowerShell cmdlet template </Description>
    <Icon> __TemplateIcon.ico </Icon>
        <Assembly> System.Management.Automation </Assembly>
    <ProjectItem SubType=""
            ReplaceParameters="true"> PowershellCmdlet.cs </ProjectItem>
Most of this is boilerplate, and you can customize a few items; check out the full schema from Microsoft in the links below.
Actual C# source code that is used to initialize the new source file you've created. Various $variable$ replacements are done to customize the item (replacing the filename, project name, etc.).
// $itemname$.cs
// Written by Steve with lots of awesome

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;

namespace $rootnamespace$
    [Cmdlet(VerbsCommon.Get, "Item")]
    public class Get_Item : PSCmdlet

If you have a header you add to all your source files, this is where to put it, along with whatever you prefer to set up your stock cmdlet (for instance, you might add the empty BeginProcessing method to be filled in).
This is the icon that shows up in the new-item dialog, and I believe I got this one from an Export-Template operation while researching this topic; I actually can't recall.
This is a link to the file I used, the graphically-adventurous may wish to make their own. I'm not that creative.

Put these two items in a ZIP file, navigate to your Documents folder, then drill down to the Visual Studio 2017\Templates\ItemTemplates\ directory, and drop the ZIP file there.

Then, when you restart Visual Studio the next time, it's available in the Add New Item:

I've highlighted in red how items in the template show up in the output add-new-item dialog, so you can tell what you're adjusting.

This has been super helpful for as many cmdlets as I write.


First published: 2019/07/29