Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
Getting the error of a Powershell Script within c# and outputting it with conditional statement?

I have a console application and a method that executes a PowerShell script within the console application. So I'm trying to grab an error text that it outputs in the application and do something with it.

Example/What I'm trying to do:

    If Error.contains("Object") 
{
    // do something here
}

Here is my current method

  public void ExecutePowershellScript()
{
  var file = @"C:\Path\filename.ps1";
           
            var start = new ProcessStartInfo()
            {
                FileName = "powershell.exe",
                Arguments = $"-NoProfile -ExecutionPolicy unrestricted -file \"{file}\"",
                UseShellExecute = false
            };
            Process.Start(start);
}
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Process.start: how to get the output?

When you create your Process object set StartInfo appropriately:

var proc = new Process 
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "program.exe",
        Arguments = "command line arguments to your executable",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

then start the process and read from it:

proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
    string line = proc.StandardOutput.ReadLine();
    // do something with line
}

You can use int.Parse() or int.TryParse() to convert the strings to numeric values. You may have to do some string manipulation first if there are invalid numeric characters in the strings you read.

over 4 years ago · Santiago Trujillo Relatório

0

You can set RedirectStandardError = true and access any errors from process.StandardError

    public static void ExecutePowershellScript()
    {
        var file = @"C:\Path\filename.ps1";

        var start = new ProcessStartInfo()
        {
            FileName = "powershell.exe",
            Arguments = $"-NoProfile -ExecutionPolicy unrestricted -file \"{file}\"",
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true
        };
        using Process process = Process.Start(start);
        string output = process.StandardOutput.ReadToEnd();
        string errors = process.StandardError.ReadToEnd();
    }



Okay, scratch the above suggestion. After being corrected by mklement0,

This is a perfectly reasonable attempt, but, unfortunately, it can lead to hangs (while waiting for one's stream end, the other, when exceeding the buffer size, may cause process execution to block). If you need to capture both streams, you must collect the output from one of them via events. – mklement0

I changed the solution to use the ErrorDataReceived event

        public static async Task ExecutePowershellScript()
        {
            var file = @"C:\Path\filename.ps1";

            var start = new ProcessStartInfo
            {
                FileName = "powershell.exe",
                Arguments = $"-NoProfile -ExecutionPolicy unrestricted -file \"{file}\"",
                UseShellExecute = false,
                // redirect standard error stream to process.StandardError
                RedirectStandardError = true
            };

            using var process = new Process
            {
                StartInfo = start
            };

            // Subscribe to ErrorDataReceived event
            process.ErrorDataReceived += (sender, e) =>
            {
                //  code to process the error lines in e.Data
            };

            process.Start();

            // Necessary to start redirecting errors to StandardError
            process.BeginErrorReadLine();

            // Wait for process to exit
            await process.WaitForExitAsync();

        }
over 4 years ago · Santiago Trujillo Relatório

0

start.Start();
while (!start.StandardOutput.EndOfStream)
{
    string line = start.StandardOutput.ReadLine();
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda