【问题标题】:Terminate Service By executing PowerShell script from Java通过从 Java 执行 PowerShell 脚本来终止服务
【发布时间】:2016-12-28 02:32:38
【问题描述】:

我正在尝试使用 Java Runtime 类执行 PowerShell 脚本,但由于某种原因没有任何反应。我也试图将 CMD 输出到我的 Java 代码,但没有成功。这是我的代码:

private void connectToServer() {
    executeCmdCommand("cd C:/PSTools");// navigate to psTools directory
    executeCmdCommand("PsExec.exe //<server1> -u orgnization/user_qa -p      sdsad1212 cmd");// connect the server machine
    executeCmdCommand("powershell.exe C:/powerShell/stop-process.ps1 MainRls");// stopr service by execute powershell script
}

/**
* execute cmd commands
*/
private void executeCmdCommand(String command){
    try {
        ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", command);
        Process process = builder.start();
        BufferedReader inputStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
        Report.assertOnReport(inputStream.readLine());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

当我从 CMD 手动执行相同的命令时,服务成功终止,但在由 Java 代码执行时它什么也不做。

【问题讨论】:

  • 您检查过 PowerShell 脚本执行策略吗?默认设置需要签名脚本。打开 Powershell 提示符并输入:Set-ExecutionPolicy RemoteSignedSet-ExecutionPolicy Unrestricted

标签: java powershell cmd


【解决方案1】:

当您手动执行命令时,这些命令会起作用,因为第二个命令会在远程主机上打开一个交互式 shell,而您正在将第三个命令键入远程主机上的那个 shell您的 Java 代码不是那样工作的,因为它单独运行两个命令。因此,您需要直接使用PsExec 运行 PowerShell 命令:

executeCmdCommand("PsExec.exe //<server1> -u orgnization/user_qa -p sdsad1212 C:/windows/system32/WindowsPowerShell/v1.0/powershell.exe -File C:/powerShell/stop-process.ps1 MainRls");

【讨论】:

  • 我试过了,连接服务器后不执行Powershell脚本
  • 那可能是因为我的答案在路径中没有转义反斜杠。我用正斜杠替换了它们。请重试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-11
  • 1970-01-01
  • 1970-01-01
  • 2012-07-25
  • 2020-05-19
  • 2023-03-10
相关资源
最近更新 更多