我需要在 C# 中创建一个类库,我想将其包含在我正在编写的 PowerShell 模块中。我想通过调用一个方法来使用 PowerShell 中的 DLL,如下所示:
Add-Type -Path $($variableHash.RootPath + "\Deviceparserstandalone.dll")
[SkypeHelpers.CQTools.DeviceParser+Audio]::IsCertified($_.Caption)
Run Code Online (Sandbox Code Playgroud)
以上是PowerShell导入DLL,然后使用该IsCertified方法的示例(我假设它是一个方法)。
这是我要找的:
目标是编写一个类库,PowerShell 可以使用该类库为 Windows 10 创建 Toast 通知。我意识到 PowerShell Gallery 上有公共模块,但我试图了解它是如何从头开始构建的。
另一种选择是制作一个完整的 PowerShell 模块。这是做到这一点的快速方法:
Microsoft.PowerShell.5.ReferenceAssemblies我的问候课:
public class GreetingClass
{
public string Greeting { get; set; }
public string ToWhom { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
System.Management.Automation.Cmdlet并带有一些 PowerShell 特定的属性:这是我的:
[Cmdlet(VerbsCommon.New, "Greeting")]
[OutputType(typeof(GreetingClass))]
public class NewGreeting : Cmdlet
{
[Parameter(Mandatory = true)]
public string Greeting { get; set; }
[Parameter]
[Alias("Who")]
public string ToWhom { get; set; } = "World";
protected override void ProcessRecord()
{
base.ProcessRecord();
WriteVerbose("Creating and returning the Greeting Object");
var greeting = new GreetingClass {Greeting = Greeting, ToWhom = ToWhom};
WriteObject(greeting);
}
}
Run Code Online (Sandbox Code Playgroud)
Debug选项卡项目属性并设置:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe-noprofile -noexit -command "import-module .\yourProjectName.dll现在按F5。将出现一个 PowerShell 控制台。由于您导入了模块,因此New-Greeting加载了cmdlet。所以这一切都有效:
PS C:\> New-Greeting -Greeting "hello there" -ToWhom World
Run Code Online (Sandbox Code Playgroud)
导致:
Greeting ToWhom
-------- ------
hello there World
Run Code Online (Sandbox Code Playgroud)
但是,您的 cmdlet 是一个完整的 PowerShell cmdlet,因此它可以进入管道。这个:
PS C:\> New-Greeting -Greeting "What's new" -ToWhom Pussycat | Format-List
Run Code Online (Sandbox Code Playgroud)
会导致:
Greeting : What's new
ToWhom : Pussycat
Run Code Online (Sandbox Code Playgroud)
由于您在按下F5并加载模块时启动了 PowerShell 会话,因此您可以在调试器中的代码、单步等中设置断点。
您将获得所有正常的 PowerShell 优点。您可以将-Who其用作-ToWhom. 该-Greeting参数被描述为Mandatory,所以如果你忘记了,控制台会提示你。
您还可以在 POCO 类上公开方法。例如,如果您将此方法添加到GreetingClass:
public void SayHello()
{
Console.WriteLine($"{Greeting} {ToWhom}");
}
Run Code Online (Sandbox Code Playgroud)
您可以在 PowerShell 中执行此操作:
PS C:\> $greet = New-Greeting -Greeting Hello -Who World
PS C:\> $greet.SayHello()
Run Code Online (Sandbox Code Playgroud)
结果如下:
Hello World
Run Code Online (Sandbox Code Playgroud)
我从中学到了很多:https : //www.red-gate.com/simple-talk/dotnet/net-development/using-c-to-create-powershell-cmdlets-the-basics/
您可以Get-Help自动从 PowerShell获得基本帮助,但如果您按照 Red-Gate 演示(来自上面的链接)进行操作,您将学习如何Get-Help从标准 C# XML 注释(来自XmlDoc2CmdletDocNuGet 包)获得丰富的帮助。