我在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();
}
}
}
}
}