简体   繁体   中英

How to run startup code in a c# powershell module

I have created a simple PowerShell module in c# which implements a few cmdlets and I would like to be able to run code when the module is imported.

From looking around on google and in the namespace there doesn't appear to be a proper way of doing this.

The work around I have come up with so far is to either create a psm1 or ps1 file that runs when the module is loaded and does the startup actions (would rather not use this as scripts are blocked on some environments this will run on).

Other option is I have been able to do it by creating a CmdletProvider which works but it creates a junk entry in the list of providers when using new-psdrive.

[CmdletProvider("junkprovider", ProviderCapabilities.None)]
public class Startup : CmdletProvider
{
    Public Startup()
    {
      // Startup code here
    }
}

Is there a way to do this properly or am I going to have to use hacks?

You can implement the System.Management.Automation.IModuleAssemblyInitializer interface.

using System.Management.Automation;

namespace MyModule
{
    public class MyModuleAssemblyInitializer : IModuleAssemblyInitializer
    {
        public void OnImport()
        {
            // Initialization code here.
        }
    }
}

The Import-Module command will call OnImport when the assembly is imported as a module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM