How to run startup code in a c# powershell module

大城市里の小女人 提交于 2019-12-11 06:55:17

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/51624686/how-to-run-startup-code-in-a-c-sharp-powershell-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!