Search code examples
javabatch-fileargumentsprocessbuilder

How to run a batch file with arguments in administrator mode from JavaSwing button using process builder?


I am creating a Java Swing application where I am taking input from user which will be used as arguments for a batch file.

After pressing a button, my batch file should get launched in ADMIN mode along with the arguments provided by user.

This is the command line:

powershell Start-Process -Verb runas cmd '/k System.getProperty("user.dir") + batchFilePath +arg1+ ""  +arg2 + "" +arg3'

This command is working properly when we paste it in CMD window.

But I want code for a Java application so that we can run it from JButton. So I used ArrayList and given this ArrayList as input to ProcessBuilder but I am getting an error.

code:

String launchCMD= System.getProperty("user.dir") + batchFilePath +arg1+ ""  +arg2 + "" +arg3
final ArrayList<String> commands = new ArrayList<String>();
commands.add("powershell Start-Process -Verb runas cmd \'/k ")
commands.add(launchCMD)
commands.add("\'" );

ProcessBuilder pr=new ProcessBuilder(commands);
pr.start();

error:

java.io.IOException: Cannot run program ... : CreateProcess error=2, The system cannot find the file specified

Solution

  • Your question is not really related to Swing, it is related to how to use class ProcessBuilder and that class is not a terminal emulator. It does not parse a command line that you enter into a PowerShell window. You need to split the command into tokens. That's why the ProcessBuilder constructor takes a list of strings. Note that the parameters to ProcessBuilder constructor do not have to be string literals. You can create a string any way you like and pass it as an argument to the ProcessBuilder constructor.

    You didn't post a sample batch file so I wrote one of my own, named showargs.bat which simply echoes its first argument.

    @echo off
    echo %1
    

    The command that worked for me (i.e. ran the batch file as administrator) was:

    powershell.exe -Command Start-Process cmd.exe -ArgumentList '/k C:\Users\USER\showargs.bat Diego' -Verb RunAs
    

    Java code that executes the above command using class ProcessBuilder:

    ProcessBuilder pb = new ProcessBuilder("powershell.exe",
                                           "-Command",
                                           "Start-Process",
                                           "cmd.exe",
                                           "-ArgumentList",
                                           "'/k C:\\Users\\USER\\showargs.bat Diego'",
                                           "-Verb",
                                           "RunAs");
    try {
        Process proc = pb.start();
        int status = proc.waitFor();
        System.out.println("status = " + status);
    }
    catch (InterruptedException | IOException x) {
        x.printStackTrace();
    }