参考:http://social.technet.microsoft.com/Forums/windowsserver/en-US/d32537bd-0aef-440e-8760-6b3085390c37/executing-powershell-script-via-java?forum=winserverpowershell
最近在尝试用Java调用Powershell, 搜了狠多资料,终于发现下面的可行方案
推荐第一种,因为对于第二种,假如命令为:& "C:\Program Files\Markin\selenium\CloseNousedApp.ps1" 就不会执行,也不报错
1 executePSScript("C:/Program Files/automationscripts/Sample/Markin/src/actions/selenium/CloseNousedApp.ps1","");
2 executePSCommand("Write-Host \"Markin\"");
public static String executePSCommand(String command) throws Exception
{
//String cmd = "cmd /c c:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell -noprofile -noexit -executionPolicy restricted Set-ExecutionPolicy -Scope Process RemoteSigned " + command;
String cmd = "cmd /c c:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell -ExecutionPolicy RemoteSigned -noprofile -noninteractive " + command;
return exec(cmd);
}
public static String executePSScript(String scriptFilename, String args) throws Exception {
if (!new File(scriptFilename).exists())
throw new Exception("Script file doesn't exist: " + scriptFilename);
String cmd = "cmd /c c:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell -ExecutionPolicy RemoteSigned -noprofile -noninteractive -file \"" + scriptFilename + "\"";
if (args != null && args.length() > 0)
cmd += " " + args;
return exec(cmd);
}
private static String exec(String command) throws Exception
{
StringBuffer sbInput = new StringBuffer();
StringBuffer sbError = new StringBuffer();
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command);
proc.getOutputStream().close();
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String line;
while ((line = bufferedreader.readLine()) != null)
{
sbInput.append(line + "\n");
}
inputstream = proc.getErrorStream();
inputstreamreader = new InputStreamReader(inputstream);
bufferedreader = new BufferedReader(inputstreamreader);
while ((line = bufferedreader.readLine()) != null)
{
sbError.append(line + "\n");
}
if (sbError.length() > 0)
throw new Exception("The command [" + command + "] failed to execute!\n\nResult returned:\n" + sbError.toString());
return "The command [" + command + "] executed successfully!\n\nResult returned:\n" + sbInput.toString();
}