Я пытаюсь выполнить набор команд в сеансе powershell через java, но пока не повезло. Моя цель - искать компьютерный объект в AD с доменом = "domain.com".Выполнение команды Powershell, связанной с ADS, через Java не работает, если у вас есть 2 разных ошибки при использовании двух разных способов.
Я начал с одной команды. К сожалению, следующая команда успешно работает в моей Powershell строке:
Get-ADComputer -Filter { Name -like "hostname" } –Server a.b.c.d:3268 -SearchBase 'DC=domain,DC=com' | FT DNSHostName
# hostname is actual hostname provided by user and accepted in argument of Java methods
# a.b.c.d is the IP-Address of my domain controller, and I'm trying to search a computer object in AD with the domain = "domain.com".
Но, он производит различные исключения/ошибки с 2 различными подходами.
Я пробовал basic way of executing powershell commands, а затем передал команду в качестве аргумента. Это не сработало, в результате возникла другая ошибка, описанная ниже.
Дальше, я пробовал использовать jPowerShell library (profesorfalken), не веря снова. Проверьте ошибку в последнем
код для первой попытки:
public String executeCommand(String hostname){
String output = "";
try{
// String firstPartCommand = "Get-ADComputer -Filter { Name -like (", secondPartCommand = ") } –Server a.b.c.d:3268 -SearchBase 'DC=domain,DC=com' | FT DNSHostName";
String firstPartCommand = "Get-ADComputer -Filter { Name -like \""+hostname+"\" } –Server a.b.c.d:3268 -SearchBase \'DC=domain,DC=com\' | FT DNSHostName";
Runtime rt = Runtime.getRuntime();
String[] cmds = new String[]{
"powershell.exe", firstPartCommand.trim()
};
System.out.println(firstPartCommand);
Process pr = rt.exec(cmds);
pr.getOutputStream().close();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(pr.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s+" -> OUTPUT");
output+=s;
//displayTF.setText(s);
}
stdInput.close();
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s+" -> ERROR");
}
stdError.close();
return output;
}
catch(Exception ex){
ex.printStackTrace(System.out);
output = "Some exception occured, SORRY!";
return output;
}
}
Выход:
Get-ADComputer -Filter { Name -like "hostname" } –Server a.b.c.d:3268 -SearchBase 'DC=domain,DC=com' | FT DNSHostName
Here is the standard output of the command:
Here is the standard error of the command (if any):
Get-ADComputer : Error parsing query: ' Name -like hostname' Error Message: 'syntax error' at position: '13'. -> ERROR At line:1 char:1 -> ERROR + Get-ADComputer -Filter { Name -like hostname} -Server a.b.c.d ... -> ERROR + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -> ERROR + CategoryInfo : ParserError: (:) [Get-ADComputer], ADFilterParsingException -> ERROR + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Micr -> ERROR osoft.ActiveDirectory.Management.Commands.GetADComputer -> ERROR -> ERROR
Код для второй попытки:
public String execute(String hostname){
String output = "";
PowerShell powershell = null;
try{
powershell = PowerShell.openSession();
// String cmd = "$variable = \""+hostname+"\"";
// //Execute a command in PowerShell session
// PowerShellResponse response = powershell.executeCommand(cmd);
// //Print results
// System.out.println("Variable Initialisation:" + response.getCommandOutput());
String firstPartCommand = "Get-ADComputer -Filter { Name -like \"", secondPartCommand = "\" } –Server 10.0.239.236:3268 -SearchBase 'DC=AD,DC=SBI' | FT DNSHostName";
String finalCommand = firstPartCommand+hostname+secondPartCommand;
System.out.println(finalCommand);
PowerShellResponse response = powershell.executeCommand(finalCommand);
//PowerShellResponse response = powershell.executeCommand("Get-Process powershell -FileVersionInfo");
output = response.getCommandOutput();
System.out.println("Search result: "+hostname+"\n" + output);
return output;
}
catch(Exception ex){
return "Failed!";
}
finally {
//Always close PowerShell session to free resources.
if (powershell != null)
powershell.close();
}
}
Выход:
Get-ADComputer -Filter { Name -like "hostname" } –Server a.b.c.d:3268 -SearchBase 'DC=domain,DC=com' | FT DNSHostName
Search result: hostname
Get-ADComputer : A positional parameter cannot be found that accepts argument '–Server'. At line:1 char:1 + Get-ADComputer -Filter { Name -like "hostname" } –Server a.b.c.d ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Get-ADComputer], ParameterBindingException + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.GetADComputer
Из того, что я искал и понял, имя хоста, который передается методу Java не получает лечение в виде строки в PowerShell. Эти ошибки относятся к powershell, с которыми я не очень разбираюсь.
EDIT: После Mathias R. Jessen's ответ, я не получаю сообщение об ошибке в 2-ом случае; но, кажется, сама библиотека не соответствует правилу.
Итак, говоря о первом методе, я получаю ошибку, как упоминалось в первом случае. Я хочу продолжить первый метод!
Я почти утратил свою веру во внешнюю JAR-панель JPowershell. Я не получаю ошибку во втором выходе; но, не получая выход. Он ведет себя так, как будто выход команды отсутствует!
Просьба помочь мне решить эту проблему!
У вас есть эм-тире в вашем втором example - замените '-Server' на' -Server' –
@ MathiasR.Jessen - Спасибо, теперь я не получаю ошибку во втором выходе; но, не получая выход. Он ведет себя так, как будто выход команды отсутствует! Также вы можете помочь вам, почему первый код не работает? –