GibboK
GibboK

Reputation: 73918

How to call a Java program from PowerShell?

I need to call a java program (jar file )from PowerShell. The following code works:

java -jar $cls --js $dcn --js_output_file $dco

But I need to have to run the app in a process (using Start-Process).

I am trying the following with no sucess:

Start-Process -FilePath java -jar $cls --js $dcn --js_output_file $dco -wait -windowstyle Normal

Error:

Start-Process : A parameter cannot be found that matches parameter name 'jar'.

Any idea how to fix it?

Upvotes: 10

Views: 70596

Answers (3)

SRJ
SRJ

Reputation: 2816

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

Upvotes: 0

Abhijeet Dhumal
Abhijeet Dhumal

Reputation: 1809

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
}

Upvotes: 21

paxdiablo
paxdiablo

Reputation: 881403

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.

Upvotes: 1

Related Questions