如何在执行前预览 PowerShell 命令?

Cli*_* Ok 7 c# powershell .net-core powershell-core

假设我有以下 PowerShell

PowerShell shell = PowerShell.Create().AddCommand("Get-NetAdapter")
                                      .AddParameter("name", "Ethernet*")
                                      .AddParameter("ThrottleLimit", 5);
Run Code Online (Sandbox Code Playgroud)

现在,在 call 之前shell.Invoke(),为了记录目的,我想检查最终的命令行。在这种情况下,我希望像

Get-NetAdapter -name Ethernet* -ThrottleLimit 5
Run Code Online (Sandbox Code Playgroud)

我测试了这些,但没有一个工作:

shell.Commands.ToString()
shell.Commands.Commands.ToString()
shell.Commands.Commands.First().CommandText
shell.Commands.Commands.First().ToString()
Run Code Online (Sandbox Code Playgroud)

是否有一些内置的方法来检查最终的命令行?

小智 7

怎么样:

namespace SomeProject.Extensions
{
    using System;
    using System.Management.Automation;
    using System.Management.Automation.Runspaces;
    using System.Text;

    public static class PowerShellExtensions
    {
        public static void LogCommandLine(this PowerShell commandToLog)
        {
            foreach (Command command in commandToLog.Commands.Commands)
            {
                StringBuilder commandLine = new StringBuilder(command.ToString());

                foreach (CommandParameter parameter in command.Parameters)
                {
                    commandLine.Append($" --{parameter.Name} {parameter.Value}");
                }

                Console.WriteLine(commandLine.ToString());
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

其中给出

namespace SomeProject.Extensions.UnitTests
{
    using System.Management.Automation;
    using NUnit.Framework;

    [TestFixture]
    [Parallelizable(ParallelScope.All)]
    [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
    public class PowerShellExtensionsTests
    {
        [Test]
        [Category(nameof(PowerShellExtensions))]
        public void TestCommandLine()
        {
            PowerShell shell = PowerShell.Create().AddCommand("Get-NetAdapter")
                                                  .AddParameter("name", "Ethernet*")
                                                  .AddParameter("ThrottleLimit", 5);

            shell.LogCommandLine();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出你想要的:

Get-NetAdapter --name Ethernet* --ThrottleLimit 5
Run Code Online (Sandbox Code Playgroud)

给定更复杂的参数,您可能需要更花哨,因为它只会输出参数的类型,而不一定是它的一个很好的字符串表示。