Pipe character from PowerShell string command is not recognized in Csharp C# code

Viewed 428

I have to execute some PowerShell commands on a remote machine from code. For that, I use .net ssh client. Everything works except pipe command interpretation. This code below returns me an error:

DEBUG: 'Stop-Process' is not recognized as an internal or external command, operable program or batch file.

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 Answers

It works if I add additional quotes:

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