我可以用.NET Core编写PowerShell二进制cmdlet吗?

bru*_*ord 12 c# powershell cmdlets .net-core

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

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

  • 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 
Run Code Online (Sandbox Code Playgroud)

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

Kei*_*ill 10

使用.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
Run Code Online (Sandbox Code Playgroud)

要在Windows PowerShell 5.1中运行此命令,需要更多工作.在命令运行之前,您必须执行以下命令:

Add-Type -Path "C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.netcore.app\2.0.0\ref\netcoreapp2.0\netstandard.dll"
Run Code Online (Sandbox Code Playgroud)

  • 现在不再需要指定“PowerShellStandard.Library”的版本。默认版本就可以了。谢谢。 (2认同)

M.H*_*san 5

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

  • 安装PowerShell标准模块模板

$ dotnet new -i Microsoft.PowerShell.Standard.Module.Template
Run Code Online (Sandbox Code Playgroud)
  • 在新文件夹中创建新模块项目
$ dotnet new psmodule
Run Code Online (Sandbox Code Playgroud)
  • 构建模块
dotnet build
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请阅读文档


Tra*_*z13 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-*"
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)