2016-08-21 78 views
0

我试图使用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代码执行它什么都不做。

+0

您是否检查过PowerShell脚本执行策略?默认设置需要签名的脚本。打开Powershell提示符并键入:'Set-ExecutionPolicy RemoteSigned'或'Set-ExecutionPolicy Unrestricted' –

回答

2

这些命令在您手动执行命令时起作用,因为第二个命令在远程主机上打开交互式shell,并且将第三个命令输入到远程主机上的该shell 你的Java代码不能这样工作,因为它单独运行两个命令。因此,您需要直接运行PowerShell命令:PsExec

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"); 
+0

我试过了,但它在连接服务器后不执行Powershell脚本 – ALiAuto

+0

您是否尝试手动(没有Java包装器)? –

+0

是的,我尝试手动,它的工作 – ALiAuto