Search code examples
c#powershelldllimportpowershell-cmdletimport-module

Cmdlet in C# binary not exporting when imported with Import-Module


I am attempting to create an interface for one of my C# programs by creating a PowerShell Cmdlet. I originally created the project (in visual studio) as a Console Application. I have switched the Output type to Class Library in the project properties and commented out the main class. Then I added a Cmdlet class in the same namespace.

using System.Management.Automation;
// various other using dependencies

namespace MyProgram
{
    // This class used to contain the main function
    class ProgramLib
    {
        // various static methods
    }

    [Cmdlet(VerbsCommon.Get, "ProgramOutput")]
    [OutputType(typeof(DataTable))]
    class GetProgramOutputCmdlet : Cmdlet
    {
        protected override void ProcessRecord()
        {
            // Code using ProgramLib methods
        }

        // Begin/End Processing omitted for brevity
    }
}

The project will build successfully and output a .dll file named MyProgram.dll.

I can then navigate to the project directory via PowerShell and import the assembly with no errors:

PS> Import-Module .\MyProgram.dll -Verbose -Force
VERBOSE: Loading module from path 'C:\my\current\path\MyProgram.dll'.
PS> 

However, it does not appear to load my Cmdlet:

PS> Get-ProgramOutput
Get-ProgramOutput : The term 'Get-ProgramOutput' is not recognized as the name of a
cmdlet, function, script file, or operable program.

Why isn't my Cmdlet exporting?

I have included both the System.Management.Automation and Microsoft.PowerShell.5.ReferenceAssemblies references in my project; the ladder via NuGet.


Solution

  • The default access modifier for a class in C# is internal. If you add "public" to your cmdlet class definition you should see your cmdlet when you import the module.

    public class GetProgramOutputCmdlet : Cmdlet