programing

Java 프로그램에서 PowerShell 명령 실행

sourcejob 2023. 10. 31. 21:09
반응형

Java 프로그램에서 PowerShell 명령 실행

저는.PowerShell Command내가 실행해야 할 것은Java프로그램.누가 이것을 어떻게 하는지 안내해 줄 수 있습니까?

내 명령은Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize

자바 프로그램은 다음과 같이 작성해야 합니다. 여기 Nirman's 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");

 }

}

파워셸 스크립트를 실행하려면

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

System.out.println(PowerShell.executeSingleCommand(command).getCommandOutput());

다음과 같은 명령을 사용하여 powershell.exe를 호출할 수 있습니다.

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

        ProcessBuilder pb = new ProcessBuilder(commandList);  

        Process p = pb.start();  

명령에서 -ExecutionPolicy RemoteSigned를 사용할 수 있습니다.

문자열 cmd = "cmd/cowershell - 실행 정책 원격 서명됨 -noprofile -non interactive C:\Users\File.ps1

언급URL : https://stackoverflow.com/questions/29545611/executing-powershell-commands-in-java-program

반응형