在Java程序中执行Vmware PowerShell命令

时间:2016-11-20 08:48:02

标签: java powershell vmware

我编写了一个执行PowerShell命令的Java程序。这是我的代码:

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

我想要做的是:我想让代码在VMware上运行的Windows Server PowerShell中执行命令,而不是在本地PowerShell中执行命令?我应该如何修改代码呢?

1 个答案:

答案 0 :(得分:0)

在远程主机上使用PowerShell invoke命令:

String server  = "remotehost";
String command = "powershell.exe -Command \"&{Invoke-Command -Computer " +
                 server + " -ScriptBlock {$PSVersionTable.PSVersion}}\"";

远程主机需要启用PSRemoting才能生效。

相关问题