Java ProcessBuilder执行错误的流程时如何获取错误代码

时间:2018-07-25 13:23:55

标签: java powershell processbuilder

我正在尝试通过processbuilder启动powershell脚本,并且我肯定在那里有错误,但是exitValue()和waitFor()之类的命令始终返回0-OK状态。对捕捉错误有任何想法吗?

P.S。我知道我可以解析和查看ErrorStream,但是..通常,ErrorStream中的某些消息适合我(它们不影响脚本),但是有些消息(powershell例外),例如未知的命令或错误的命令或连接错误,应该让我知道有一个严重的错误

P.P.S。我的代码如下:

Process process = null;
String path = "Path\\To\\PowershellScript.ps1"
    int isErrorProcess = 0;
    int isErrorProcess1 = 0;
    try {
        ProcessBuilder pb = new ProcessBuilder("powershell.exe", path);
        pb.directory(new File(path.substring(0, path.lastIndexOf("\\"))));
        pb.redirectErrorStream(true);
        process = pb.start();            
        ProcessBuilder.Redirect rd = pb.redirectError();
        // Get input streams
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream(),"866"));

        // Read command standard output + error
        String s;

        System.out.println("\nOutput:\n");
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        isErrorProcess = process.exitValue();
        if(isErrorProcess == 0 && isErrorProcess1 == 0){ //why always 0 even if powershell script with erros
            isErrorStatus = false;
        }
        process.destroy();
        return isErrorStatus;

    } catch (Exception e) {
        process.destroy();
        e.printStackTrace(System.err);
        return true;
    }

非常感谢

0 个答案:

没有答案