PowerShell字符串命令中的管道符在C#代码中无法识别

3

我需要在代码中远程执行一些PowerShell命令。为此,我使用.net ssh客户端。除了管道命令解释之外,一切都有效。下面的代码会返回一个错误:

DEBUG:'Stop-Process'未被识别为内部或外部命令、可操作程序或批处理文件。

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
            }
        }
    }
}

1
问题不在于管道字符。您正在尝试通过SSH启动CMD脚本,该脚本使用原始 Powershell脚本启动Windows Powershell可执行文件,这对CMD毫无意义。 - Panagiotis Kanavos
1
如果您想远程执行 Powershell,请使用 Powershell 远程。在 Windows 上,它可以通过 WinRM 实现,而不是 SSH(一开始就不可用)。在 Linux 和 Powershell Core 上,它可以通过 SSH 实现。 - Panagiotis Kanavos
如果你使用的是Windows 10或Windows Server 2019,SSH远程连接也可以使用。但对于客户机来说这是透明的,你不需要SshClient,也不能通过Windows可执行文件使用它。 - Panagiotis Kanavos
@PanagiotisKanavos,你可能应该把这些评论整理成一个答案。我已经点赞了OP的回答,因为它有效并且有用,但是你提出的那个(或者那些)更加简洁明了。 - Pac0
@PanagiotisKanavos,您能否给我提供测试代码示例? - Tatiana
显示剩余4条评论
1个回答

0

如果我添加额外的引号,它就可以工作:

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

它实际上并没有。没有必要像这样使用powershell.exe,它已经提供了安全的远程控制功能。Windows Powershell已经被Powershell Core所取代,所以在某些情况下可能会无法使用powershell.exe。而且它绝对不会在Linux上工作。 - Panagiotis Kanavos
另一方面,使用远程操作,您只需编写 Get-Process -ComputerName thatComputer notepad - Panagiotis Kanavos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接