【问题标题】:Can I write PowerShell binary cmdlet with .NET Core?我可以使用 .NET Core 编写 PowerShell 二进制 cmdlet 吗?
【发布时间】:2017-02-15 17:15:54
【问题描述】:

我正在尝试使用二进制 Cmdlet 内部创建一个基本的 PowerShell 模块,因为仅在 PowerShell 中编写内容看起来不像在 C# 中那样方便。

按照this 指南,看来我必须:

  • Microsoft.PowerShell.SDK 添加到我的project.json
  • 用必需的属性标记我的 cmdlet 类
  • 写清单文件,用RootModule,针对我的.dll
  • .dll 放在附近的清单中
  • 将两者都放在PSModulePath

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

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 

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

【问题讨论】:

标签: c# powershell .net-core cmdlets


【解决方案1】:

使用.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 中,非常感谢!
  • 现在不再需要指定PowerShellStandard.Library 的版本。默认版本才有效。谢谢。
【解决方案2】:

对于netcore,有一个新的powershell模板,你可以安装和使用,然后你可以修改c#代码。

  • 安装 PowerShell 标准模块模板

$ dotnet new -i Microsoft.PowerShell.Standard.Module.Template
  • 在新文件夹中创建新模块项目
$ dotnet new psmodule
  • 构建模块
dotnet build

更多详情请阅读doc

【讨论】:

    【解决方案3】:

    您需要使用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-*"
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-07
      • 2011-07-11
      • 2012-01-11
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      • 2010-09-20
      相关资源
      最近更新 更多