您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Java程序中执行PowerShell命令

在Java程序中执行PowerShell命令

您应该编写一个这样的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\" ";
java 2022/1/1 18:17:03 有502人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶