Creating Modules

There are Script modules (.psm1 files) and Binary modules (aka cmdlets)

Script Module

A script module is essentially any valid PowerShell script saved in a .psm1 extension.

function Show-Calendar {
}
Export-ModuleMember -Function Show-Calendar

The paths where you can install your module are located in the $env:PSModulePath global variable. Be sure to create a folder for your module to exist in, even if it is only a single .psm1 file

By default, all functions in your script are accessible to users who import your .psm1 file, but properties are not.

Binary (C#) Module

Make a class library (dll)

You have to import the module by dll name: Import-Module BinModuleTest\PSbinModule.dll

using System.Management.Automation;           // Windows PowerShell namespace.

namespace ModuleCmdlets
{
    [Cmdlet(VerbsDiagnostic.Test, "BinaryModuleCmdlet1")]
    public class TestBinaryModuleCmdlet1Command : Cmdlet
    {
        protected override void BeginProcessing()
        {
            WriteObject("BinaryModuleCmdlet1 exported by the ModuleCmdlets module.");
        }
    }

    [Cmdlet(VerbsDiagnostic.Test, "BinaryModuleCmdlet2")]
    public class TestBinaryModuleCmdlet2Command : Cmdlet
    {
        protected override void BeginProcessing()
        {
            WriteObject("BinaryModuleCmdlet2 exported by the ModuleCmdlets module.");
        }
    }

    [Cmdlet(VerbsDiagnostic.Test, "BinaryModuleCmdlet3")]
    public class TestBinaryModuleCmdlet3Command : Cmdlet
    {
        protected override void BeginProcessing()
        {
            WriteObject("BinaryModuleCmdlet3 exported by the ModuleCmdlets module.");
        }
    }

}

You invoke the cmdlet like this: “Test-BinaryModuleCmdlet1”

Debugging Binary PS Modules

If you’re using Visual Studio (and making a .NET Framework library), right click on the csproj and add this to the Debug command line args: -noexit -command "&{ import-module .\[dllName].dll -verbose}"

Reference: https://www.powershellmagazine.com/2014/04/08/basics-of-writing-a-powershell-module-with-c-part-2-debugging/

If you are making a .NET Standard library, you’ll have to add a post build event: add dotnet publish --no-build to the post build event and change the command line argument to reference .\publish\[dllName].dll

The post build event copies all the dlls (in nuget packages) that you reference (like json.net) into the output folder.

Original stackoverflow answer

get yourself on the email list

//Powered by MailChimp - low volume, no spam

comments powered by Disqus