我们试图通过Java调用Powershell脚本,但是当我们尝试读取该脚本的输出时它会挂起。它挂在“input.readLine()”
上以下是我们尝试的代码:
String command = "cmd /c powershell C:\\_checkouts\\TestPowerShell\\passwordExpirationTime.ps1";
Process p = Runtime.getRuntime().exec(command);
new InputStreamReader(p.getInputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();;
for (String line = input.readLine(); line != null; line = input.readLine()) {
stringBuilder.append(line);
}
input.close();
String msg = stringBuilder.toString();
System.out.println("msg: " + msg);
我们尝试查看此解决方案Java program hangs when trying to invoke powershell script 但这些建议都不适合我们。
我们也尝试过没有cmd / c和cmd / k。我们真的希望这是一个可以调用任何脚本的泛型类。即BAT,BASH,SH,Powershell等
有什么想法吗?
感谢下面的答案,这里的代码是有效的:
try{
final ProcessBuilder pb = new ProcessBuilder("powershell","C:\\psFile.ps1");
pb.redirectInput(Redirect.from(new File("NUL")));
final Process p = pb.start();
final int retcode = p.waitFor();
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}catch (Exception e){
e.printStackTrace();
}
以下是一些其他信息。我们的powershell因为受到限制而返回错误。这就是我们需要所有重定向到NUL的原因。一旦我们修复了它并且没有返回错误,我们就可以将代码简化为:
try{
final ProcessBuilder pb;
pb = new ProcessBuilder(args);
final Process p = pb.start();
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}catch (Exception e){
e.printStackTrace();
}
答案 0 :(得分:1)
使用ProcessBuilder
。任何暗示一点I / O的过程都应该直接拒绝通过Runtime.exec()
运行,唉,它无法检测到这一点。而甲骨文没有将其标记为@Deprecated
,这是一个遗憾。
反正:
final File logFile = new File("/path/to/logfile");
final ProcessBuilder pb = new ProcessBuilder("powershell", "/path/to/the/ps1");
pb.redirectOutput(Redirect.to(logFile));
pb.redirectErrorStream(true);
final Process p = pb.start();
final int retcode = p.waitFor();
// deal with retcode
// read result from the log file