Выполнение команд PowerShell в программе Java

У меня есть PowerShell Command который мне нужно выполнить с помощью Java программа. Кто-нибудь может подсказать мне, как это сделать?

Моя команда Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize

3 ответа

Решение

Вы должны написать такую ​​Java-программу, вот пример, основанный на техническом блоге Nirman, основная идея - выполнить команду, вызывающую процесс PowerShell, следующим образом:

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");

 }

}

Для того, чтобы выполнить скрипт powershell

String command = "powershell.exe  \"C:\\Pathtofile\\script.ps\" ";

Не нужно изобретать велосипед. Теперь вы можете просто использовать jPowerShell

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

powerShell = PowerShell.openSession();

//Print results    
System.out.println(powerShell.executeCommand(command).getCommandOutput());

powerShell.close();

Вы можете попробовать вызвать powershell.exe с помощью следующих команд:

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

        ProcessBuilder pb = new ProcessBuilder(commandList);  

        Process p = pb.start();  

Вы можете использовать -ExecutionPolicy RemoteSigned в команде.

Строка cmd = "cmd /c powershell -ExecutionPolicy RemoteSigned -noprofile -noninteractive C:\Users\File.ps1

Другие вопросы по тегам