简体   繁体   English

如何在ac#powershell模块中运行启动代码

[英]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. 我在c#中创建了一个简单的PowerShell模块,该模块实现了几个cmdlet,并且我希望能够在导入模块时运行代码。

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). 到目前为止,我想出的解决方法是创建一个psm1或ps1文件,该文件在加载模块并执行启动操作时运行(而不是使用此文件,因为脚本将在某些将要运行的环境中被阻止)。

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来做到这一点,但是使用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. 您可以实现System.Management.Automation.IModuleAssemblyInitializer接口。

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. 当程序集作为模块导入时, Import-Module命令将调用OnImport

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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