Java keytool.exe powershell wrapper does not suppress standard errors

Viewed 2623

I am trying to write some keytool wrappers in Powershell for managing keystores. The issue I am facing, is that in Powershell, when running a command similar to:

$cmd = "& " + $keytoolexe + " -import " + $CAswitch +
" -alias "    + $alias + 
" -keystore " + $keystore + " -storepass " + $storepass + 
" -file "     + $file +
" -noprompt *>&1" 
$result = Invoke-Expression -Command $cmd

As you can see I am redirecting everything to standard ouptut, as I want to store that in a variable to evaluate the result of the command.

The problem is that when keytool.exe returns a successful message, powershell somehow reads it as error.

I tried to run the block-code, itself, and I did not get any, error. However after I put this code inside a function and I invoked the function with parameter -ErrorAction stop, i got this error.

keytool.exe : Certificate was added to keystore
At line:1 char:1
+ & "C:\Program Files\Emulex\OCM for VMware\JRE\bin\keytool.exe" -impor ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Certificate was added to keystore:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

So somehow ErrorAction Stop seems to make the standard ouptut redirection disappear.

2 Answers

I am not sure I fully understand, how it works, but after a lot of "monkey testing" I now have what I am looking for:

$cmd = "& " + $keytoolexe + " -import " + $CAswitch +
" -alias "    + $alias + 
" -keystore " + $keystore + " -storepass " + $storepass + 
" -file "     + $file +
" -noprompt *>&1" 
$dummy = Invoke-Expression -Command $cmd -ErrorVariable KeyToolStdOut -OutVariable KeyToolStdErr -ErrorAction Continue

Somehow it seems this combination of redirecting everything to standard ouptut (*>&1) and then using variables to capture standard output and standard error works.

And yes, I put standard ouptut as errorvariable on purpose, the code above, does just that, sends what i believe should be standard output to error, and error to standard output.

Then i'm using logic in the scripts to determine success or failure. I hope this helps someone out there, and I'm hoping someone explains why what I just uncovered works.

Don't do it in Powershell ISE. Use the regular powershell.

Related