Search code examples
javapowershellprocessruntime.execioexception

Error while run the powershell command


How to invoke the powershell command using java.

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

note : i map the correct path.

I tried with the above code but it gives the error like

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))

Anyone could you please help on this.


Solution

  • Environment Variables are not always exposed to the java compiler. Your stack error is just telling you it cannot find the powershell executable, because it doesn't automatically know to look in the $PSHOME var.

    The fix is just to specify the full path:
    Change "powershell.exe" to "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"