C#二进制文件中的Cmdlet不与Import-Module一起导出

时间:2019-06-26 14:14:12

标签: c# powershell dllimport cmdlet import-module

我试图通过创建PowerShell Cmdlet为我的一个C#程序创建一个接口。我最初是在Console Application中创建项目的(在Visual Studio中)。我在项目属性中将输出类型切换为Class Library,并注释掉了主类。然后,我在同一名称空间中添加了Cmdlet类。

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
    }
}

该项目将成功构建并输出名为.dll的{​​{1}}文件。

然后我可以通过PowerShell导航到项目目录并导入程序集而不会出现错误:

MyProgram.dll

但是,它似乎没有加载我的Cmdlet:

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

为什么我的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. # Insert rest of generic 'CommandNotFoundException' here System.Management.Automation引用;通过NuGet爬梯子。


答案:

我的类定义缺少访问修饰符,默认将其设置为内部类。要解决此问题,我必须将Microsoft.PowerShell.5.ReferenceAssemblies类设为Cmdlet

public

1 个答案:

答案 0 :(得分:3)

C#中类的默认访问修饰符是内部的。如果在cmdlet类定义中添加“ public”,则在导入模块时应该会看到cmdlet。

public class GetProgramOutputCmdlet : Cmdlet