我可以使用.NET Core编写PowerShell二进制命令吗?

18

我正在尝试创建一个基本的PowerShell模块,它具有二进制Cmdlet内部,因为仅使用PowerShell编写的东西看起来不如在C#中方便。

根据指南,似乎我必须:

  • Microsoft.PowerShell.SDK添加到我的project.json
  • 用需要的属性标记我的cmdlet类
  • 编写清单文件,具有RootModule,目标是我的.dll
  • 将该.dll放在附近的清单下
  • 将两者都放在PSModulePath

但是,当我尝试Import-Module时,PowerShell core抱怨缺少运行时:

Import-Module : Could not load file or assembly 'System.Runtime, Version=4.1.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system
cannot find the file specified.
At line:1 char:1 

我是否做错了什么,或者这些棘手的事情还不被支持?


你能分享一下你的 project.json 吗? - Ben Force
看看这个能否帮到你!https://dev59.com/gJjga4cB1Zd3GeqPP9ME https://dev59.com/IVsX5IYBdhLWcg3wcPKw#37639003 - Prageeth Saravanan
抱歉,目前这不是实际情况。 - brutallord
3个回答

13

如果您使用.NET Core 2.0 SDKVisual Studio 2017 Update 15.3(或更高版本),这将变得容易得多。如果您没有VS,可以使用.NET Core 2.0 SDK从命令行执行此操作。

重要的部分是将PowerShellStandard.Library 3.0.0-preview-01(或更高版本)NuGet包添加到项目文件(.csproj)中。

这里是一个简单的命令行示例:

cd $home
dotnet new classlib --name psmodule
cd .\psmodule
dotnet add package PowerShellStandard.Library --version 3.0.0-preview-01
Remove-Item .\Class1.cs
@'
using System.Management.Automation;

namespace PSCmdletExample
{
    [Cmdlet("Get", "Foo")]
    public class GetFooCommand : PSCmdlet
    {
        [Parameter]
        public string Name { get; set; } = string.Empty;

        protected override void EndProcessing()
        {
            this.WriteObject("Foo is " + this.Name);
            base.EndProcessing();
        }
    }
}
'@ | Out-File GetFooCommand.cs -Encoding UTF8

dotnet build
cd .\bin\Debug\netstandard2.0\
ipmo .\psmodule.dll
get-foo

要在Windows PowerShell 5.1中运行相同的命令需要更多的工作。在执行该命令之前,您必须执行以下操作:

Add-Type -Path "C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.netcore.app\2.0.0\ref\netcoreapp2.0\netstandard.dll"

Add-Type 部分帮助我将 .NET Standard 库加载到 PowerShell 中,非常感谢! - Vitaliy Ulantikov
2
现在不再需要指定 PowerShellStandard.Library 的版本。默认版本就可以工作了。谢谢。 - Israfel

4

针对 Netcore,现已推出新的 PowerShell 模板,您可以安装并使用它,然后修改 C# 代码。

  • 安装 PowerShell 标准模板

$ dotnet new -i Microsoft.PowerShell.Standard.Module.Template

在新文件夹中创建一个新的模块项目。
$ dotnet new psmodule
  • 构建模块
dotnet build

了解更多详情请阅读文档


1

你需要使用 PowerShell Core 来在 .NET Core 中编写 PowerShell CmdLet。

这里有一份指南,包括对你的 project.json 的更正: https://github.com/PowerShell/PowerShell/tree/master/docs/cmdlet-example

总结来说,你需要在你的 project.json 文件中添加以下内容:

    "dependencies": {
        "Microsoft.PowerShell.5.ReferenceAssemblies": "1.0.0-*"
    },

    "frameworks": {
        "netstandard1.3": {
            "imports": [ "net40" ],
            "dependencies": {
                "Microsoft.NETCore": "5.0.1-*",
                "Microsoft.NETCore.Portable.Compatibility": "1.0.1-*"
            }
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接