How to call a Java program from PowerShell? How to call a Java program from PowerShell? powershell powershell

How to call a Java program from PowerShell?


You will need to use following format for powershell:

 Start-Process java -ArgumentList '-jar', 'MyProgram.jar' `-RedirectStandardOutput '.\console.out' -RedirectStandardError '.\console.err' 

Or other option you can use is Start-job:

Start-Job -ScriptBlock {  & java -jar MyProgram.jar >console.out 2>console.err}


It looks like the -jar is being picked up as an argument of Start-Process rather than being passed through to java.

Although the documentation states that -ArgumentList is optional, I suspect that doesn't count for -option-type things.

You probably need to use:

Start-Process -FilePath java -ArgumentList ...

For example, in Powershell ISE, the following line brings up the Java help (albeit quickly disappearing):

Start-Process -FilePath java -argumentlist -help

but this line:

Start-Process -FilePath java -help

causes Powershell itself to complain about the -help.


Option 1 [Using Start-Job ScriptBlock]

Start-Job -ScriptBlock {  & java -cp .\Runner.jar com.abc.bcd.Runner.java >console.out 2>console.err}if ( $? == "True")   write-host("Agent started successfully")else if ($? == "False")   write-host("Agent did not start")

Option 2 [Using Start-Process]

Start-Process -FilePath '.\jre\bin\java' -WindowStyle Hidden -Wait -ArgumentList "-cp .\Runner.jar com.abc.bcd.Runner"

That's how i did it using above two options initially.

Option 3 [Using apache-commons-daemon]

I can suggest a better and robust alternative.

You can use apache-commons-daemon library to build a windows service for your java application and then start, stop the service very conveniently.

There is amazing youtube video which will explain apache commons daemon and how to build a windows service. I will attach the reference at the end.

References :

https://commons.apache.org/proper/commons-daemon/index.html

https://www.youtube.com/watch?v=7NjdTlriM1g