Share via


Why Won’t My Custom Cmdlets Appear?

Once again, I’ve been puzzled multiple times as to why my custom cmdlets sometimes don’t appear in PowerShell after I’ve added them via Add-PSSnapIn.  The last post didn’t stick with me, so a little more detail to drill it into my thick skull this time…

As it turns out, Cmdlets must have a public default constructor, of course!   I sometimes forget this step when I’m in my TDD rhythm.  So something like this:

 using System.Management.Automation;

namespace MyCmdlets
{
    [Cmdlet(VerbsCommon.New, "DooDad")]
    public class NewDooDadCommand : MyBaseCommand
    {
        [Parameter(Position = 0, Mandatory = true)]
        public string MyData { get; set; }

        private readonly IDooDadFactory _dooDadFactory;
         public NewDooDadCommand(IDooDadFactory dooDadFactory )
        {
            _dooDadFactory = dooDadFactory;
        }

        ...
    }
}

Should really look more like this:

 using System.Management.Automation;

namespace MyCmdlets
{
    [Cmdlet(VerbsCommon.New, "DooDad")]
    public class NewDooDadCommand : MyBaseCommand
    {
        [Parameter(Position = 0, Mandatory = true)]
        public string MyData { get; set; }

        private readonly IDooDadFactory _dooDadFactory;
         /// <summary>
        /// Need this public default constructor
        /// </summary>
        public NewDooDadCommand()
            :this(ServiceLocator.GetInstance<IDooDadFactory>())
        {}
         public NewDooDadCommand(IDooDadFactory dooDadFactory )
        {
            _dooDadFactory = dooDadFactory;
        }

        ...
    }
}