在 C# 中获取此 Powershell 输出的正确方法是什么

问题描述

我在下面没有收到任何错误,但我也没有得到输出。下面是 Powershell cmd 和调用它的 C# 方法。我想知道它是否编写正确,以及如何获得来自 powershell 的输出。当我从 PowerShell 窗口运行时它工作正常

密码命令:

public class GetRowAndPartitionKeys : Cmdlet
    {
        [Parameter(Mandatory = false)]
        public List<string> Properties { get; set; } = new List<string>();
    }

    [Cmdlet( VerbsCommon.Get,"RowAndPartitionKeys" )]
    public class GetRowAndPartitionKeyCmd : GetRowAndPartitionKeys

    {
        protected override void ProcessRecord()
        {            
            WriteObject ("Hi");
        }
    }

}

C# 方法

 public async Task<IEnumerable<object>> RunScript(  )
        {
            // create a new hosted PowerShell instance using the default runspace.
            // wrap in a using statement to ensure resources are cleaned up.
           string scriptContents = "Import-Module 'C:\Users\...\Powershell.dll";
            using( PowerShell ps = PowerShell.Create() )
            {
                // specify the script code to run.
            ps.AddScript( scriptContents ).AddCommand( "Get-RowAndPartitionKeys" );


            // execute the script and await the result.
            var pipelineObjects = await ps.InvokeAsync().ConfigureAwait( false );
           
            foreach( var item in pipelineObjects )
            {
                Console.WriteLine( item.BaSEObject.ToString() );
            }
            return pipelineObjects;
        }

解决方法

answer to your previous question 类似,以下自包含示例代码表明该方法在纠正代码中的以下问题后原则上有效:

  • .AddStatement().AddScript() 调用之间缺少 .AddCommand() 调用;这对于(基于脚本块的)Import-Module 调用和 Get-RowAndPartitionKeys 调用被视为单独的语句是必要的。

  • 伪代码行 string scriptContents = "Import-Module 'C:\Users\...\Powershell.dll"; 缺少结束 '(可能只是在这里发帖的产物)。

  • 此外,下面还添加了故障排除代码。

虽然编排代码在 PowerShell 中,实际的 C# 项目,通过 .NET SDK 编译,结合 PowerShell (Core ) SDK 包,Microsoft.PowerShell.SDK

运行创建和运行测试项目的代码后,您可以自己检查和试验它们7.1.2 是模块 DLL 的项目,它定义了 {{1 }} cmdlet,./module 是调用它的应用程序的项目):

Get-RowAndPartitionKeys

在我的 Windows 10 机器上(从 PowerShell 7.1.2 运行),我得到:

results

如您所见:

  • 详细输出确认 cmdlet 已正确导入
  • ./app 显示该 cmdlet 已成功调用。