22

I have a PowerShell Command which I need to execute using Java program. Can somebody guide me how to do this?

My command is Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize

question
  • 392
  • 1
  • 4
  • 15
  • possible duplicate of [Execute Powershell script using java](http://stackoverflow.com/questions/17467676/execute-powershell-script-using-java) – tnw Apr 09 '15 at 17:57
  • Yes,I have gone through that question but can you give me a basic examle to set me going? I want to learn this. – question Apr 09 '15 at 18:00
  • 1
    You need to exercise your google-fu and look up some examples. There's no reason you can't at least make an attempt at researching this. – tnw Apr 09 '15 at 18:18

4 Answers4

38

You should write a java program like this, here is a sample based on Nirman's Tech Blog, the basic idea is to execute the command calling the PowerShell process like this:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class PowerShellCommand {

 public static void main(String[] args) throws IOException {

  //String command = "powershell.exe  your command";
  //Getting the version
  String command = "powershell.exe  $PSVersionTable.PSVersion";
  // Executing the command
  Process powerShellProcess = Runtime.getRuntime().exec(command);
  // Getting the results
  powerShellProcess.getOutputStream().close();
  String line;
  System.out.println("Standard Output:");
  BufferedReader stdout = new BufferedReader(new InputStreamReader(
    powerShellProcess.getInputStream()));
  while ((line = stdout.readLine()) != null) {
   System.out.println(line);
  }
  stdout.close();
  System.out.println("Standard Error:");
  BufferedReader stderr = new BufferedReader(new InputStreamReader(
    powerShellProcess.getErrorStream()));
  while ((line = stderr.readLine()) != null) {
   System.out.println(line);
  }
  stderr.close();
  System.out.println("Done");

 }

}

In order to execute a powershell script

String command = "powershell.exe  \"C:\\Pathtofile\\script.ps\" ";
user2518618
  • 1,360
  • 13
  • 32
anquegi
  • 11,125
  • 4
  • 51
  • 67
  • 1
    In case the path to the/a `.ps1` file contains a space, you can modify the `command` to: ```String command1 = "powershell.exe & 'C:/test folder with spaces/yourPowershellScript.ps1' ";``` to run the script from eclipse. – a.t. Jun 05 '19 at 15:14
  • 2
    Just incase someone would like to execute multiple commands at one time, use `-and` or `-or` between your commands to connect them. – Wayne Wei Aug 23 '20 at 16:25
24

No need of reinvent the wheel. Now you can just use jPowerShell. (Disclosure: I am the author of this tool.)

String command = "Get-ItemProperty " +
                "HKLM:\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* " +
                "| Select-Object DisplayName, DisplayVersion, Publisher, InstallDate " +
                "| Format-Table –AutoSize";

System.out.println(PowerShell.executeSingleCommand(command).getCommandOutput());
daveloyall
  • 2,140
  • 21
  • 23
profesor_falken
  • 559
  • 6
  • 10
  • 1
    I found your JAR to be not that robust, check my question + answer ---> http://stackoverflow.com/questions/42065666/executing-ads-related-powershell-command-through-java-does-not-work-giving-2-dif – Am_I_Helpful Feb 08 '17 at 09:41
  • 1
    Hello, for what I understand your problem was basically in the command string you sent to jPowershell and not in the JAR itself. – profesor_falken Feb 24 '17 at 22:55
  • Just came across this post and comment. I tried jPowerShell and got a couple simple examples working so just wanted to give my anecdotal endorsement of solution. Thanks @profesor_falken – MarkyMarksFunkyBunch Oct 21 '20 at 18:03
  • Is there anyway to use this library to execute commands which require admin privileges such as Disable-PnpDevice and Enable-PnpDevice? – Ron McLeod Aug 30 '23 at 21:57
5

you can try to calle the powershell.exe with some commands like :

String[] commandList = {"powershell.exe", "-Command", "dir"};  

        ProcessBuilder pb = new ProcessBuilder(commandList);  

        Process p = pb.start();  
Katarak
  • 79
  • 2
-3

You can use -ExecutionPolicy RemoteSigned in the command.

String cmd = "cmd /c powershell -ExecutionPolicy RemoteSigned -noprofile -noninteractive C:\Users\File.ps1

Kumar Saurabh
  • 2,297
  • 5
  • 29
  • 43