
本文旨在解决 PowerShell 脚本在命令行环境下成功执行,但在 Java 代码中调用时却无法正常工作的问题。通过分析 Java 代码中调用 PowerShell 脚本的方式,以及 PowerShell 命令行参数的传递规则,提供一种正确的解决方案,确保脚本在 Java 环境中也能顺利执行。本文将详细讲解如何正确构建命令行参数,以及在使用 Runtime.getRuntime().exec() 方法时需要注意的关键点。
在 Java 中执行 PowerShell 脚本时,经常会遇到脚本在命令行中运行正常,但在 Java 代码中却无法正确执行的问题。这通常是由于命令行参数传递不正确导致的。Runtime.getRuntime().exec() 方法对参数的处理方式与直接在命令行中执行命令有所不同。
关键在于将构成 PowerShell 命令行的所有参数作为单独的数组元素传递给 Runtime.getRuntime().exec() 方法。
例如,以下代码展示了错误的参数传递方式:
立即学习“Java免费学习笔记(深入)”;
String[] command = new String[]{"powershell.exe","-ExecutionPolicy Unrestricted -file 'C:\Users\xxxyyy\Downloads\test_script.ps1' -d 'C:\Users\xxxyyy\Downloads' -f 'TestFile'"};正确的做法是将每个参数都作为独立的字符串元素添加到数组中:
String[] command = new String[]{
"powershell.exe",
"-ExecutionPolicy",
"Unrestricted",
"-file",
"C:\Users\xxxyyy\Downloads\test_script.ps1",
"-d",
"C:\Users\xxxyyy\Downloads",
"-f",
"TestFile"
};这样,Java 才能正确地将每个参数传递给 PowerShell 进程。
下面是修正后的 Java 代码示例:
import org.junit.jupiter.api.Test;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class PowershellTest {
@Test
public void shouldConvertXlsxToCsv() {
try {
runCommand();
} catch (IOException e) {
e.printStackTrace();
}
}
public void runCommand() throws IOException {
String scriptPath = "C:\Users\xxxyyy\Downloads\test_script.ps1";
String directory = "C:\Users\xxxyyy\Downloads";
String filename = "TestFile";
String[] command = new String[]{
"powershell.exe",
"-ExecutionPolicy",
"Unrestricted",
"-file",
scriptPath,
"-d",
directory,
"-f",
filename
};
Process powerShellProcess = Runtime.getRuntime().exec(command);
powerShellProcess.getOutputStream().close();
BufferedReader output = new BufferedReader(new
InputStreamReader(powerShellProcess.getInputStream(), StandardCharsets.ISO_8859_1));
try {
String line;
while ((line = output.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}在 Java 中执行 PowerShell 脚本,关键在于正确构建传递给 Runtime.getRuntime().exec() 方法的命令行参数。确保将每个参数作为独立的数组元素传递,可以避免因参数解析错误而导致脚本执行失败的问题。此外,注意 PowerShell 脚本本身的路径和参数传递方式,确保脚本在 Java 环境中能够顺利执行。
以上就是PowerShell 脚本在命令行工作,但在 Java 代码中不工作?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号