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#.

4
  • possible duplicate of Capturing Powershell output in C# after Pipeline.Invoke throws Commented Aug 1, 2014 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... Commented Aug 1, 2014 at 19:40
  • What exactly is Invoke-MyCmd? Commented Aug 1, 2014 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. Commented Aug 1, 2014 at 21:57

1 Answer 1

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;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.