运行 powershell 命令时出错

Sat*_*iya 0 java powershell process runtime.exec ioexception

如何使用java调用powershell命令。

  try {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(20000);
        Process powerShellProcess = Runtime.getRuntime().exec(
                "powershell.exe \"D:\\testscript.ps1\"");
        if (watchdog != null) {
            watchdog.start(powerShellProcess);
        }
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(
                powerShellProcess.getInputStream()));
        String line;
        System.out.println("Output :");
        while ((line = stdInput.readLine()) != null) {
            System.out.println(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

注意:我映射了正确的路径。

我尝试使用上面的代码,但它给出了类似的错误

java.io.IOException: Cannot run program "powershell.exe": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:459)
    at java.lang.Runtime.exec(Runtime.java:593)
    at java.lang.Runtime.exec(Runtime.java:431)
    at java.lang.Runtime.exec(Runtime.java:328)
    at com.powershell.PsJava.main(PsJava.java:17))
Run Code Online (Sandbox Code Playgroud)

任何人都可以请你帮忙。

Col*_*350 5

环境变量并不总是暴露给 java 编译器。您的堆栈错误只是告诉您它找不到 powershell 可执行文件,因为它不会自动知道查看 $PSHOME 变量。

修复只是指定完整路径:
更改"powershell.exe""C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"