我試圖使用Java運行時類執行PowerShell腳本,但由於某種原因沒有任何反應。我也試圖將CMD輸出到我的Java代碼,但沒有成功。這是我的代碼:終止服務通過執行Java中的PowerShell腳本
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 RemoteSigned'或'Set-ExecutionPolicy Unrestricted' –