Подтвердить что ты не робот

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

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

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

4b9b3361

Ответ 1

Вам следует написать такую ​​java-программу, вот пример, основанный на Nirman Tech Blog, основная идея состоит в том, чтобы выполнить команду, вызывающую процесс 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 script

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

Ответ 2

Не нужно изобретать велосипед. Теперь вы можете просто использовать 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());

Ответ 3

вы можете попытаться вызвать файл powershell.exe с помощью некоторых команд, например:

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

        ProcessBuilder pb = new ProcessBuilder(commandList);  

        Process p = pb.start();  

Ответ 4

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

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