Kian
Kian

Reputation: 221

Powershell script does not run in Java code

I have a simple script and I want to call it from my Java code. The script does not run properly.

The script is very simple: mkdir 0000000;

public static void main(String[] args) throws Exception{
    String path = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
    String command = "C:\\test\\test.ps1";
    Runtime runtime = Runtime.getRuntime();
    Process proc = runtime.exec(path + " " + command);
    proc.destroy();
}

The dir "0000000" is not created. I use JDK 7, windows 10.

Any suggestion would be gratefully appreciated.

Upvotes: 0

Views: 1228

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

exec() runs the process asynchronously, so the subsequent proc.destroy() terminates it right away before it can do anything. If you run the program from an interactive shell simply removing proc.destroy() would mitigate the issue, but to actually fix it you need to wait for the external process to finish. You may also want to catch the exception exec() (or waitFor()) could throw.

import java.io.*;

public static void main(String[] args) throws Exception{
    String path = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
    String command = "C:\\test\\test.ps1";
    Runtime runtime = Runtime.getRuntime();
    try {
        Process proc = runtime.exec(path + " " + command);
        proc.waitFor();
    } catch (Exception e) {
        // do exception handling here
    }
}

Upvotes: 1

Kian
Kian

Reputation: 221

I changed the code as below and finally it worked!

    public static void main(String[] args) throws Exception{
        String path = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
        String command1 ="cmd /c \"cd C:\\test && " + path + " /c .\\test.ps1\"";
        Runtime runtime = Runtime.getRuntime();
        Process proc = runtime.exec(command1);
        Thread.sleep(2000);
        proc.destroy();
    }

Upvotes: 1

Related Questions