Я пытаюсь создать интерфейс для одной из моих программ на C #, создав командлет PowerShell. Я изначально создал проект (в visual studio) как Console Application
. Я переключил тип вывода на 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
с именем MyProgram.dll
.
Затем я могу перейти в каталог проекта через PowerShell и импортировать сборку без ошибок:
PS> Import-Module .\MyProgram.dll -Verbose -Force
VERBOSE: Loading module from path 'C:\my\current\path\MyProgram.dll'.
PS>
Однако он не загружает мой командлет:
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
и Microsoft.PowerShell.5.ReferenceAssemblies
; Лестница через NuGet.
Ответ:
В моем определении класса отсутствовал модификатор доступа, по умолчанию это был внутренний класс. Чтобы исправить, я должен был сделать мой Cmdlet
класс public
:
[Cmdlet(VerbsCommon.Get, "ProgramOutput")]
[OutputType(typeof(DataTable))]
public class GetProgramOutputCmdlet : Cmdlet
{
}