10

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?

GibboK
  • 71,848
  • 143
  • 435
  • 658
  • Knowing what the actual problem is, I would say that would be a nice thing to have in order to be able to fix it. "No success" is hardly the most verbose problem report I've ever seen :-) – paxdiablo Feb 24 '15 at 08:56

3 Answers3

21

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
}
ycomp
  • 8,316
  • 19
  • 57
  • 95
Abhijeet Dhumal
  • 1,799
  • 13
  • 24
1

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • thanks for your answer, could you please provide me an example using my code, I have problem in setting argumentlist – GibboK Feb 24 '15 at 09:24
0

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

SRJ
  • 2,092
  • 3
  • 17
  • 36