本文旨在解决 PowerShell 脚本在命令行环境下成功执行,但在 Java 代码中调用时却无法正常工作的问题。通过分析 Java 代码中调用 PowerShell 脚本的方式,以及 PowerShell 命令行参数的传递规则,提供一种正确的解决方案,确保脚本在 Java 环境中也能顺利执行。本文将详细讲解如何正确构建命令行参数,以及在使用 Runtime.getRuntime().exec() 方法时需要注意的关键点。
在 Java 中执行 PowerShell 脚本时,经常会遇到脚本在命令行中运行正常,但在 Java 代码中却无法正确执行的问题。这通常是由于命令行参数传递不正确导致的。Runtime.getRuntime().exec() 方法对参数的处理方式与直接在命令行中执行命令有所不同。
正确构建 PowerShell 命令参数
关键在于将构成 PowerShell 命令行的所有参数作为单独的数组元素传递给 Runtime.getRuntime().exec() 方法。
例如,以下代码展示了错误的参数传递方式:
立即学习“Java免费学习笔记(深入)”;
String[] command = new String[]{"powershell.exe","-ExecutionPolicy Unrestricted -file 'C:UsersxxxyyyDownloadstest_script.ps1' -d 'C:UsersxxxyyyDownloads' -f 'TestFile'"};
正确的做法是将每个参数都作为独立的字符串元素添加到数组中:
String[] command = new String[]{ "powershell.exe", "-ExecutionPolicy", "Unrestricted", "-file", "C:UsersxxxyyyDownloadstest_script.ps1", "-d", "C:UsersxxxyyyDownloads", "-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:UsersxxxyyyDownloadstest_script.ps1"; String directory = "C:UsersxxxyyyDownloads"; 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(); } } } }
PowerShell 脚本注意事项
- -File 参数与引号: powershell.exe 使用 -File 参数时,不会像 -Command 参数那样解析单引号 ‘…’ 字符串。 因此,应避免在传递给 -File 的路径中使用单引号。
总结
在 Java 中执行 PowerShell 脚本,关键在于正确构建传递给 Runtime.getRuntime().exec() 方法的命令行参数。确保将每个参数作为独立的数组元素传递,可以避免因参数解析错误而导致脚本执行失败的问题。此外,注意 PowerShell 脚本本身的路径和参数传递方式,确保脚本在 Java 环境中能够顺利执行。
评论(已关闭)
评论已关闭