【问题标题】:Pipe character from PowerShell string command is not recognized in Csharp C# codeCsharp C# 代码中无法识别来自 PowerShell 字符串命令的管道字符
【发布时间】:2020-03-09 16:22:49
【问题描述】:

我必须通过代码在远程机器上执行一些 PowerShell 命令。为此,我使用 .net ssh 客户端。除了管道命令解释外,一切正常。下面的这段代码给我一个错误:

调试:“停止进程”未被识别为内部或外部 命令、可运行的程序或批处理文件。

using System.IO;

using Or1WinAppDriverTests.Properties;

using Renci.SshNet;

using Xunit;
using Xunit.Abstractions;

namespace Or1WinAppDriverTests.aidaTests {

    public class AidaMachineSshAccessTests
    {
        public AidaMachineSshAccessTests(ITestOutputHelper output)
        {
            this._output = output;
        }

        private readonly ITestOutputHelper _output;

        [Fact]
        public void SshTest3()
        {
            var host = Resources.HOST;
            var username = Resources.USERNAME;
            var password = Resources.PASSWORD;

            using (var client = new SshClient(host, username, password))
            {
                #region Example SshCommand CreateCommand Execute ExtendedOutputStream

                client.Connect();

                var cmd2 = client.CreateCommand(
                    $"powershell.exe -executionPolicy bypass ;" +
                    $"Get-Process notepad | Stop-Process ;" +
                    $"exit ;");

                var result = cmd2.Execute();

                _output.WriteLine(result);

                var reader = new StreamReader(cmd2.ExtendedOutputStream);
                _output.WriteLine("DEBUG:");
                _output.WriteLine(reader.ReadToEnd());

                client.Disconnect();

                #endregion Example SshCommand CreateCommand Execute ExtendedOutputStream
            }
        }
    }
}

【问题讨论】:

  • 问题不在于管道字符。您正在尝试通过 SSH 启动一个 CMD 脚本,该脚本使用一个对CMD 没有意义的 raw Powershell 脚本启动 Windows Powershell 可执行文件
  • 如果要远程执行 Powershell,请使用Powershell remoting。在 Windows 上,这适用于 WinRM,而不是 SSH(一开始不可用)。在 Linux 和 Powershell Core 上,它可以工作 over SSH
  • 如果您使用 Windows 10 或 Windows Server 2019,还可以使用通过 SSH 进行远程处理。不过,这对客户来说是透明的。您不需要 SshClient,也不能通过 Windows 可执行文件使用它。
  • @PanagiotisKanavos 您可能应该从这些 cmets 中做出答案。我赞成 OP 的答案,因为它有效,因此很有用,但是您建议的答案要干净得多。
  • @PanagiotisKanavos 能否给我代码示例进行测试?

标签: c# powershell pipe ssh.net


【解决方案1】:

如果我添加额外的引号,它会起作用:

var cmd2 = client.CreateCommand(
                    "powershell.exe -executionPolicy bypass; " +
                    "\"Get-Process notepad | Stop-Process\"; " +
                    "exit ;");

【讨论】:

  • 其实不然。没有必要像这样使用powershell.exe,它已经提供安全远程处理。 Windows Powershell 已经被 Powershell Core 取代,所以 powershell.exe 在某些时候可能会或可能不会工作。它肯定不适用于 Linux。
  • 另一方面,远程处理你可以写Get-Process -ComputerName thatComputer notepad
猜你喜欢
  • 1970-01-01
  • 2017-12-31
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 2014-03-24
  • 2019-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多