1

I know that Invoke-MyCmd throws an error and writes a message to standard error.

Let's say it's one line that invokes a Java program like this:

function Invoke-MyCmd
{
  java Error
}

Error.java just prints an error message and exits:

import java.io.*;
public class Error {
  public static void main(String[] args) {
    System.err.println("Hello, error!");
  }
}

I'm invoking Invoke-MyCmd from C# like so:

PowerShell ps = PowerShell.Create();
.
.
.
ps.AddCommand("Invoke-MyCmd");
Collection<PSObject> output = ps.Invoke();

The error text, I'm assuming because it comes from Java and not directly from Invoke-MyCmd, doesn't show up in ps.Streams.Error. I'm wondering if there's another way to read that error output from C#.

dmeyerson
  • 495
  • 4
  • 13
  • possible duplicate of [Capturing Powershell output in C# after Pipeline.Invoke throws](http://stackoverflow.com/questions/1233640/capturing-powershell-output-in-c-sharp-after-pipeline-invoke-throws) – Tsukasa Aug 01 '14 at 19:23
  • Thanks, looking at that, it doesn't quite answer my question. The first solution suggests that there should in fact be something in ps.Streams.Error after I invoke MyCmd, but there isn't. Very confusing... – dmeyerson Aug 01 '14 at 19:40
  • What exactly is `Invoke-MyCmd`? – Eris Aug 01 '14 at 20:17
  • It's a function that executes a Java executable. I realize now that might have something to do with the problem and I've updated the question. – dmeyerson Aug 01 '14 at 21:57

1 Answers1

2

I'm blatantly copy/pasting this answer using this blog as a reference

Since this is a native executable being run by powershell, you need to translate the error code into an exception like so:

'Starting script...' | Write-Verbose
$ErrorActionPreference = 'Stop'
java Thing
if ($LastExitCode -ne 0) { 
    throw 'An error has occurred...' 
}
'Finished script' | Write-Verbose

Your java application should also return non-zero when an error occurs.

import java.io.*;
public class Error {
  public static void main(String[] args) {
    System.err.println("Hello, error!");
    return 1;
  }
}
Eris
  • 7,378
  • 1
  • 30
  • 45