Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell process hanging when called from Java application

I am trying to write a simple application that takes in a command line arguement (which will be a Powershell ps1 file) and then run it. So I have experemented with a number of different approaches and seem to be running into a problem. If I attempt to invoke powershell from within java, the windows process is started and is visible via process explorer, however powershell never returns, it hangs in some sort of loop by the looks of it. The command I am using is:

            String command = "powershell -noprofile -noninteractive \"&C:\\new\\tst.ps1\"";

The command is then executed using:

Runtime systemRuntime = Runtime.getRuntime();
Process proc = systemRuntime.exec(command);

At the moment I am hard coding the location to the ps1 file as I was trying to rule this out as an issue. Using a process explorer I can see the hanging powershell process and the command that was passed to it was :

powershell -noprofile -noninteractive "&C:\new\tst.ps1"

which when copied into a cmd window, works to launch the tst.ps1 file. The file itself is incredibly simple in this example and I think I can rule it out being the cause of the freeze as I have tried to launch other ps1 files the same behaviour can be seen.

To further add to the confusion, if I use the java code posted above and pass in powershell commands instead of a file name then it successfully runs.

I've scoured the web and see lots of people experiencing the same issue but no one seems to have posted there solution, I hope its a simple oversight on my part and can be easily fixed.

Any hints/tips are appreciated :D

Alan

like image 334
Alan Avatar asked Jan 20 '11 10:01

Alan


1 Answers

You have to close OutputStream in order for Powershell to exit.

Runtime systemRuntime = Runtime.getRuntime();
Process proc = systemRuntime.exec(command);

proc.getOutputStream().close();
like image 61
Kiril Avatar answered Sep 28 '22 17:09

Kiril