1

我在java中执行powershell命令,我写了两个程序,但是奇怪的部分是一个工作正常,另一个抛出错误。抛出错误的代码如图

我尝试了以下 1) 指定 powershell 的完全指定路径 2) 我的路径变量具有以下内容 - "C:\WINDOWS\system32\WindowsPowerShell\v1.0"

我知道我可能正在做一些微不足道的事情,但已经过了一天,我无法弄清楚问题可能是什么

import java.io.IOException;

public class FileCount {

public static void main(String[] args) {
    Process flCntProcess = null;
    try {

        String test  = "C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe  -Command \"& { Get-ChildItem C:\\test -Recurse -force | Measure-Object }\"";
        System.out.println("Powershell command : " + test);
        ProcessBuilder builder = new ProcessBuilder(test);
        builder.redirectErrorStream(true);
        flCntProcess = builder.start();

        //  FILE COUNT OUTPUT STREAM PROCESSING
        NotifyThreadComplete outputThread = new ProcessHandler(flCntProcess.getInputStream(),"OUTPUT");
        outputThread.addListener(new ThreadCompleteListener() {

            @Override
            public void notifyCompletion(Thread t, long startTm, boolean didErrorOut, String noOfLines) {
                System.out.println("Completed Output Stream Processing");
                System.out.println("Printing values");
                System.out.println("No of Lines : " + noOfLines);
                System.out.println("Did Error out : " + didErrorOut);

                if(didErrorOut) {
                    System.out.println("Do not continue with processing");
                } else {
                    System.out.println("Continue with processing");
                }
            }
        });
        System.out.println("Starting output thread ");
        outputThread.start();

    } catch (Exception e) {
        System.err.println("Exception while counting files using Powershell Command" + e.getMessage());
    } finally {
        if(flCntProcess != null && flCntProcess.getOutputStream() != null) {
            try {
                flCntProcess.getOutputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
}
4

2 回答 2

1

错误代码表示找不到要执行的文件。尝试将程序与其参数分开:

String ps  = "C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe";
String args  = "-Command \"& { Get-ChildItem C:\\test -Recurse -force | Measure-Object}\"";        
ProcessBuilder builder = new ProcessBuilder(ps, args);
于 2013-10-29T15:05:21.380 回答
0

的构造函数ProcessBuilder接受包含 cli 调用的单个字符串,而是包含 in order 的字符串数组:

  • 要执行的程序
  • 它的论点

请参阅 javadoc

因此,它将您的整个字符串解释test为程序名称,将其拆分应该可以工作:

final String psh = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
final String args = "-Command & { Get-ChildItem C:\\temp -Recurse -force | Measure-Object }";
final ProcessBuilder builder = new ProcessBuilder(psh, args);
于 2013-10-29T15:07:46.063 回答