Java – How do I run the following Powershell commands in java?

How do I run the following Powershell commands in java?… here is a solution to the problem.

How do I run the following Powershell commands in java?

I’m trying to run the PowerShell command that starts the Tomcat service. Currently, the command works fine when executed directly through Windows powershell. However, if I run the same command from Java, I get an error message

Start-Process : A positional parameter cannot be found that accepts argument ‘net’.

My PowerShell command is:

Start-Process -verb runas cmd -ArgumentList "/k net start Tomcat7"

My java code:

final String PS_COMMAND = " powershell.exe  Start-Process -verb runas cmd -ArgumentList /k net start Tomcat7   " ;
Process p=  Runtime.getRuntime().exec(PS_COMMAND);
 BufferedReader BR=new BufferedReader(new InputStreamReader(p.getInputStream()));
             String l;
             while((l=BR.readLine()) != null){
                 System.out.print(l);
             }

Solution

Runtime.exec is obsolete. Use the opposite of ProcessBuilder:

ProcessBuilder builder = new ProcessBuilder("powershell.exe",
    "Start-Process", "-verb", "runas", "cmd", "-ArgumentList", "/k net start Tomcat7");
Process p = builder.inheritIO().start();
int exitCode = p.waitFor();

Call inheritIO(). Causes the output of the process to be displayed in the output of the Java program, so there is no need to read and print the InputStream of the process.

Related Problems and Solutions