Tuesday 17 June 2014

Invoke powershell commands through java

Yes, this is possible ! One can invoke powershell cmdlets from a java program and see the results. Possible solution is to execute the powershell process and run the powershell cmdlets from command line using the java 'Runtime' class. 

One approach is to write powershell scripts and have them executed from the program to see the output. Another way is to provide the command directly as string. This way we can create commands dynamically to execute at run-time as required.

Here is the program-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ExecuteCommand {

 /**
  * @param args
  * @throws IOException 
  */
 public static void main(String[] args) throws IOException {
  String command = "powershell.exe  $PSVersionTable.PSVersion";
  Process powerShellProcess = Runtime.getRuntime().exec(command);
  powerShellProcess.getOutputStream().close();
  String line;
  System.out.println("Output:");
  BufferedReader stdout = new BufferedReader(new InputStreamReader(
    powerShellProcess.getInputStream()));
  while ((line = stdout.readLine()) != null) {
   System.out.println(line);
  }
  stdout.close();
  System.out.println("Error:");
  BufferedReader stderr = new BufferedReader(new InputStreamReader(
    powerShellProcess.getErrorStream()));
  while ((line = stderr.readLine()) != null) {
   System.out.println(line);
  }
  stderr.close();
  System.out.println("Done");

 }

}

It just finds out the powershell version installed on your machine and displays the result on console.

To execute powershell scripts, we just need to have 
String command = "powershell.exe  \"C:\\PowerShellVersion.ps1\" ";

We need to provide location for the script file to be executed. You can get the source code from here.

Thanks.

5 comments:

  1. Hey can you pls explain the code in detail.. It would be very useful.. Thanks in advance.

    ReplyDelete
  2. Can we run those commands in remote server?

    ReplyDelete
  3. how can we read the file produced by powershell script by its output through java

    ReplyDelete
  4. shja iki mika bura sata kaka

    ReplyDelete
  5. Your articles are inventive. I am looking forward to reading the plethora of articles that you have linked here. Thumbs up! PS5Home

    ReplyDelete