I using PowerShell to call a Java CLI application.
I'd like to be able to capture Java errors and handle them in PowerShell. I'm simulating this by trying to get the version of Java.
If I use a valid argument (--version
)
# --version - print product version to the output stream and exit
Start-Process -FilePath java -NoNewWindow -ArgumentList '--version' -RedirectStandardOutput ~\Desktop\stdout.txt
stdout.txt
contains the expected text:
Get-Content ~\Desktop\stdout.txt
openjdk 11.0.3 2019-04-16
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.3+7)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.3+7, mixed mode)
If I use an invalid argument (-v
)
# -v; invalid argument
Start-Process -FilePath java -NoNewWindow -ArgumentList '-v' -RedirectStandardError ~\Desktop\stderr.txt
stderr.txt
contains the expected text:
Get-Content ~\Desktop\stderr.txt
Unrecognized option: -v
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
Unfortunately, I can't seem to get this to work in a try/catch block:
try {
# exception isn't raised
Start-Process -FilePath java -NoNewWindow -ArgumentList '-v' -ErrorAction Stop
}
catch {
Write-Host "ERROR: $( $_.Exception.Message )" -ForegroundColor Red
}
Is there a way to get this to work as I would like?