The PowerShell process hangs when invoked from a Java application

I'm trying to write a simple application that accepts command line arguments (which will be a power shell PS1 file) and then runs it So I have developed many different methods and seem to have encountered problems If I try to invoke PowerShell from Java, start the windows process and see it through process resource manager, but Power Shell will never return, it will hang up in some way. The commands I use are:

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

Then execute the command using the following command:

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

At present, I am trying to encode the location as PS1 file because I try to eliminate this as a problem Using the process explorer, I can see the suspended PowerShell process and the commands passed to it are:

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

When copying to the CMD window, you can start TST PS1 file In this example, the file itself is very simple, and I think I can exclude it from the reason because I try to start other PS1 files to see the same behavior

To further add confusion, if I use the Java code published above and pass in a PowerShell command instead of a file name, it will run successfully

I have browsed the Internet and saw many people encounter the same problem, but no one seems to publish the solution there. I hope it is a simple oversight for me and can be easily repaired

Any tips / hints are appreciated: D

Allen

Solution

You must close OutputStream to exit PowerShell

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

proc.getOutputStream().close();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>