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);
2
  • 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. Commented Jan 30, 2020 at 9: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 Commented Jan 30, 2020 at 9:25

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.