2

I am trying to run a Powershell script (PS1) file from my java program.

Here's my Java code :

 for     (  ;  ; )  {
     ProcessBuilder pb = new ProcessBuilder("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -Command \"C:\\Java_Scratch2\\University.PS1"); 
     Process p = pb.start();
     p.waitFor();   
    }   

but when I try to execute, I get the following error in Windows CMD :

C:\Java_Scratch2>java ParentClassBatchRunner
java.io.IOException: Cannot run program "C:\Windows\System32\WindowsPowerShell\v
1.0\powershell.exe -Command "C:\Java_Scratch2\University.PS1": CreateProcess err
or=2, The system cannot find the file specified
        at java.lang.ProcessBuilder.start(Unknown Source)
        at ParentClassBatchRunner.main(ParentClassBatchRunner.java:16)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find th
e file specified
        at java.lang.ProcessImpl.create(Native Method)
        at java.lang.ProcessImpl.<init>(Unknown Source)
        at java.lang.ProcessImpl.start(Unknown Source)
        ... 2 more

I've tried to change formatting of it, swapping ~ for spaces, etc. But still stuck . thanks

1 Answer 1

4

You have misquoted one argument.

But anyway, you should not use this form of ProcessBuilder. Invoke it like this:

final ProcessBuilder pb = new ProcessBuilder(
    "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
    "-Command",
    "C:\\Java_Scratch2\\University.PS1"
);

final Process p = pb.start();

// and don't forget to check the result of p.waitFor()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so very much !
Isn't "-File" option more suitable in such case?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.