0

I'd like to execute powershell commands in .NET framework, handling output and errors, but the following code failed executing any "complex"command.

    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.RedirectStandardInput = true;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.WorkingDirectory = IsRoot(location);
    process.StartInfo.Arguments = string.Concat("/C powershell.exe /C ", cmd);
    process.Start();
    process.WaitForExit();
    string output = process.StandardOutput.ReadToEnd();
    string error = process.StandardError.ReadToEnd();
    process.Close();

    return (output, error);
  • That's not who you execute Powershell commands or *any* commands. To execute any program, pass the *program's* name to `FileName`, not `cmd.exe`. Pass any actual arguments to `Arguments`. This means `FileName='powershell.exe'` and `Arguments = whatever`. – Panagiotis Kanavos Jan 30 '20 at 09:21
  • Powershell itself though is written in .NET. You can create a Powershell pipeline and execute Powershell commands from code directly, you don't need to launch another process. Besides, Powershell has error, progress, info and other streams that aren't accessible from Process – Panagiotis Kanavos Jan 30 '20 at 09:25

0 Answers0