having trouble capturing java keytool output within powershell

my team and I have been working on script in powershell that will find old versions of Java jre\jdk and update them to the latest version. We have been able to get the script to to complete 98% of all that we want to accomplish but seem to be having trouble with one section of the script. A small portion of the script calls the java keytool excecutable to find and old keystore and update new keystore. We have the commands to complete the task and can successfully import the new keystore when we know the keystore password, but if we don’t know the password we want to be able to capture output on the failed pasword and store it in our running log file but allow the script to continue.

$tempstore = "C:\Program Files\Java\Tempstore"

     $newcertpath = "C:\Program Files\Java\jre1.8.0_231"

     $oldcertpath = "C:\Program Files\Java\jre1.8.0_201"

     $JavaKeyTool = "C:\Program Files\Java\jre1.8.0_231\bin\keytool.exe"

     # copy cert from old path and store in temp location

     Get-ChildItem -Path $oldcertpath -Filter "cacerts" -File |

     Copy-Item  -Destination $tempstore -Recurse -Force -ErrorAction Stop

     Write-Output "Copied old x64 certs to temp file"  

     Write-Output $oldcertPath

        #import keytool from new to old

        & $JavaKeyTool -importkeystore -srckeystore "$oldcertpath\lib\security\cacerts" -srcstorepass badpassword   -destkeystore "C:\Program Files\Java\Tempstore" -deststorepass badpassword -noprompt 

        # import from updated old to new cert path Keystore

        & $JavaKeyTool -importkeystore -srckeystore "C:\Program Files\Java\Tempstore" -srcstorepass badpassword  -destkeystore "$oldcertpath\lib\security\cacerts" -deststorepass badpassword -noprompt 

If the password is incorrect we get the following output: “keytool error: java.io.IOException: Keystore was tampered with, or the password was incorrect”

This is expected but we cannot figure out how to get that output and store it in the logfile that capture all of the progress of the script. We have tried to leverage Try/Catch but can’y seem to get the syntax correct.

It is not really a java keytool issue, it is a matter of capturing the output and getting into the logfile.

Can anyone provide insight?

You need to redirect standard error to standard output. It would be the same in cmd.

dir foo
Get-ChildItem: Cannot find path '/Users/js/foo/foo' because it does not exist.

dir foo 2>&1 > log

And if you are in a loop use >> to append.

I also ran into a similar issue running a JAR file from PS. The method I chose was to use Start-Process with -RedirectStandardOutput and -RedirectStandardError to run the JAR file. Maybe overkill but it works for me.