Pregunta

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.

¿Fue útil?

Solución

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"

Otros consejos

You can run the PowerShell command using the ProcessBuilder from Java.

ProcessBuilder builder =
    new ProcessBuilder("powershell.exe", "/c", "Get-Process");
Process p = builder.start();

If the powershell executable IS in your path then make sure that you have not accidentally have Use secret text(s) or file(s) selected with specific username password credentials in the Build Environment section. I'm not sure why but this seemed to cause this issue when building on our slave!

Yes, we need to configure that the environment variable for Powershell.exe is in the path C:\Windows\System32\WindowsPowerShell\v1.0 and then restart the system.

After, that, execute the PowerShell command or script.

I test all answers above and didnot worked ! try this one ... I have this problem and it was so so suffering :)) I can solve this problem in this way: first I add C:\Windows\System32\WindowsPowerShell\v1.0 to my System path in environment variables in windows 10, after that I restart my Pc, after restarting I create a new scala sbt project but I choose scala version 11.10 and sbt version 0.0.3x instead of 1.x.x and It worked , wish you best !

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top