A execução do comando Powershell relacionado ao ADS por Java não funciona, fornecendo 2 erros diferentes ao usar 2 maneiras diferentes
Eu tenho tentado executar um conjunto de comandos em uma sessão do PowerShell através de java, sem sorte ainda. Meu objetivo é pesquisar um objeto de computador no AD com o domínio = "domínio.com".
Comecei com um único comando. Infelizmente, o seguinte comando é executado com êxito no meu prompt do 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".
Mas, produz exceções / erros diferentes com 2 abordagens diferentes.
Eu tentei omaneira básica de executar comandos do PowerShelle, em seguida, passando o comando como argumento para ele. Isso não funcionou, resultou em um erro diferente descrito abaixo.
Em seguida, tentei usarBiblioteca jPowerShell (profesorfalken) sem sorte novamente. Verifique o erro no último
Código para a primeira tentativa:
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;
}
}
Resultado:
Get-ADComputer -Filter {Nome semelhante a "hostname"} - Servidor a.b.c.d: 3268 -SearchBase 'DC = domínio, DC = com' | FT DNSHostName
Aqui está a saída padrão do comando:
Aqui está o erro padrão do comando (se houver):
Get-ADComputer: Erro ao analisar a consulta: 'Nome como hostname' Mensagem de erro: 'erro de sintaxe' na posição: '13'. -> ERRO Na linha: 1 caractere: 1 -> ERRO + Get-ADComputer -Filter {Nome semelhante ao host}} - Servidor abcd ... -> ERRO + ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~ -> ERRO + CategoriaInfo: ParserError: (:) [Get-ADComputer], ADFilterParsingException -> ERRO + FullyQualifiedErrorId: ActiveDirectoryCmdlet: Microsoft.ActiveDirectory.Management.ADFilterParsingException, Micr -> ERROR osoft.ActiveManager.Commander. GetADComputer -> ERRO -> ERRO
Código para segunda tentativa:
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();
}
}
Resultado:
Get-ADComputer -Filter {Nome semelhante a "hostname"} - Servidor a.b.c.d: 3268 -SearchBase 'DC = domínio, DC = com' | FT DNSHostName
Resultado da pesquisa: hostname
Get-ADComputer: Não foi possível encontrar um parâmetro posicional que aceite o argumento '–Server'. Na linha: 1 caractere: 1 + Get-ADComputer -Filter {Nome-como "hostname"} - Servidor abcd ... + ~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ InvalidArgument: (:) [Get-ADComputer], ParameterBindingException + FullyQualifiedErrorId: PositionalParameterNotFound, Microsoft.ActiveDirectory.Management.Commands.GetADComputer
Pelo que pesquisei e entendi, o nome do host que é passado para o método Java não está sendo tratado como uma string no PowerShell. Esses erros são referentes ao PowerShell, com o qual não tenho muita experiência.
EDITAR: Depois deMathias R. Jessen resposta, não estou recebendo nenhum erro no segundo caso; mas parece que a própria biblioteca não está correta até o momento.
Então, falando sobre o primeiro método, estou recebendo o erro conforme mencionado no primeiro caso. Eu quero continuar apenas com o primeiro método!
Quase perdi minha fé no jPowershell JAR externo. Não estou recebendo o erro na segunda saída; mas, nem obtendo a saída. Comporta-se como se não houvesse saída do comando!
Pedido para gentilmente me ajudar a resolver este problema!