从Java应用程序调用时,Powershell进程挂起 [英] Powershell process hanging when called from Java application

查看:520
本文介绍了从Java应用程序调用时,Powershell进程挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简单的应用程序,它接受一个命令行参数(将是一个Powershell ps1文件),然后运行它。所以我已经开发了许多不同的方法,似乎遇到了问题。如果我尝试从java中调用powershell,则启动windows进程并通过进程资源管理器可见,但是powershell永远不会返回,它会以某种形式挂起。我使用的命令是:

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);

目前我正在努力将位置编码为ps1文件,因为我试图将其排除在外作为一个问题。使用进程资源管理器,我可以看到挂起的powershell进程和传递给它的命令是:

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"

复制到cmd窗口时,用于启动tst.ps1文件。在这个例子中,文件本身非常简单,我认为我可以将其排除在原因之外,因为我试图启动其他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.

为了进一步增加混乱,如果我使用上面发布的java代码并传入powershell命令而不是文件名,那么它就会成功运行。

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我已经浏览过网络,看到很多人遇到同样的问题,但似乎没有人在那里发布解决方案,我希望它对我来说是一个简单的疏忽,可以很容易地修复。

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.

感谢任何提示/提示:D

Any hints/tips are appreciated :D

Alan

推荐答案

你必须关闭OutputStream以便Powershell退出。

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

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

proc.getOutputStream().close();

这篇关于从Java应用程序调用时,Powershell进程挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆