【发布时间】:2013-08-11 17:12:48
【问题描述】:
我有一个 java 应用程序,它最终会深入到外部流程集成中,包括带有这些流程的 IPC。不过现在,我要做的只是从 java 运行一个 powershell 脚本。
我有什么:
private void runPowershellScript() {
String command =
"" + "powershell" + " ";
// Paths.get("").toAbsolutePath() + "\\" + scriptFileName + " " +
// Paths.get("").toAbsolutePath() + "\\" + INPUT_FILE_NAME + " " +
// Paths.get("").toAbsolutePath() + "\\" + OUTPUT_FILE_NAME + "";
try {
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
Process process = builder.start();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine ()) != null) {
System.out.println ("Stdout: " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
根据您在此处看到的内容,我会通过该阅读器获得 Windows Powershell 名称和版权,但如果我添加任何注释掉的行(所有这些都解析为正确的路径,例如 C:\Users\Geoff\Code\OPTIP\FakeProgram.ps1),我会得到:
java.io.IOException: Cannot run program "powershell C:\Users\Geoff\Code\OPTIP\FakeProgram.ps1 ": CreateProcess error=2, The system cannot find the file specified
我尝试了十几种不同的强引号和弱引号组合,并尝试将它们作为参数传递给cmd.exe /c powershell ...,但我没有尝试运行脚本。如果命令字符串中有一个空格,我会得到一个 IO 异常。
我想知道它是否与字符编码有关?当我简单地调用 powershell 时,我从reader.readLine() 得到'返回是:
W\u0000i\u0000n\u0000 ... 我认为这是我的 IDE(IntelliJ)告诉我它的“Windows Powershell”的方式,每个字母之间有一个空 unicode 字符。
Java ProcessBuilder documentation 对您可以作为参数传递的确切内容有点模糊:
一个命令,一个字符串列表,表示要调用的外部程序文件及其参数,如果有的话。哪些字符串列表代表有效的操作系统命令取决于系统。例如,每个概念参数通常是该列表中的一个元素,但在某些操作系统中,程序需要自己标记命令行字符串——在这样的系统上,Java 实现可能需要命令恰好包含两个元素。
我不知道那是什么意思。我试图给它的命令可以在 CMD 和 Powershell 窗口中运行,也可以在 windows 运行对话框中运行。
gist 包含上述方法的类: https://gist.github.com/Groostav/9c5913e6f4696a25430d 包含我的 powershell 脚本的要点: https://gist.github.com/Groostav/347a283ac7ec6a738191
感谢您的帮助。
【问题讨论】:
标签: java powershell command-line-arguments ioexception processbuilder