Executing PowerShell Commands in Java Program

前端 未结 4 1737
醉梦人生
醉梦人生 2020-11-30 07:08

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-ItemP

相关标签:
4条回答
  • 2020-11-30 07:11

    You can use -ExecutionPolicy RemoteSigned in the command.

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

    0 讨论(0)
  • 2020-11-30 07:19

    No need of reinvent the wheel. Now you can just use jPowerShell

    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());
    
    0 讨论(0)
  • 2020-11-30 07:22

    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\" ";
    
    0 讨论(0)
  • 2020-11-30 07:36

    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();  
    
    0 讨论(0)
提交回复
热议问题