La ejecución del comando Powershell relacionado con ADS a través de Java no funciona dando 2 errores diferentes cuando se usan 2 formas diferentes

He estado intentando ejecutar un conjunto de comandos en una sesión de PowerShell a través de Java, sin suerte todavía. Mi objetivo es buscar un objeto de computadora en AD con el dominio = "dominio.com".

Empecé con un solo comando. Desafortunadamente, el siguiente comando se ejecuta con éxito en mi indicador de 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".

Pero, produce diferentes excepciones / errores con 2 enfoques diferentes.

He probado elforma básica de ejecutar comandos de PowerShell, y luego pasarle el comando como argumento. Eso no funcionó, resultó en un error diferente que se describe a continuación.

Luego, intenté usarBiblioteca jPowerShell (profesorfalken) Sin suerte otra vez. Comprueba el error en el último

Código para el primer intento:

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;
        }
    }

Salida:

Get-ADComputer -Filter {Name -like "hostname"} –Server a.b.c.d: 3268 -SearchBase 'DC = dominio, DC = com' | FT DNSHostName

Aquí está la salida estándar del comando:

Aquí está el error estándar del comando (si lo hay):

Get-ADComputer: Error al analizar la consulta: 'Nombre de host similar al nombre' Mensaje de error: 'error de sintaxis' en la posición: '13'. -> ERROR En línea: 1 char: 1 -> ERROR + Get-ADComputer -Filter {Nombre -como hostname} -Server abcd ... -> ERROR + ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~ -> ERROR + CategoryInfo: ParserError: (:) [Get-ADComputer], ADFilterParsingException -> ERROR + FullyQualifiedErrorId: ActiveDirectoryCmdlet: Microsoft.ActiveDirectory.Management.ADFilterParsingException, Micr -. GetADComputer -> ERROR -> ERROR

Código para el segundo intento:

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();
        }
    }

Salida:

Get-ADComputer -Filter {Name -like "hostname"} –Server a.b.c.d: 3268 -SearchBase 'DC = dominio, DC = com' | FT DNSHostName

Resultado de búsqueda: hostname

Get-ADComputer: no se puede encontrar un parámetro posicional que acepte el argumento '–Server'. En la línea: 1 char: 1 + Get-ADComputer -Filter {Name -like "hostname"} –Server abcd ... + ~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo: Argumento inválido: (:) [Get-ADComputer], ParameterBindingException + FullyQualifiedErrorId: PositionalParameterNotFound, Microsoft.ActiveDirectory.Management.Commands.GetADComputer

Por lo que he buscado y entendido, el nombre de host que se pasa al método Java no se trata como una cadena en el PowerShell. Estos errores pertenecen a powershell, con el que no tengo mucha experiencia.

EDITAR: DespuésMathias R. Jessen's responda, no obtengo ningún error en el segundo caso; pero, parece que la biblioteca en sí no es correcta hasta la marca.

Entonces, hablando del primer método, obtengo el error como se menciona en el primer caso. ¡Quiero seguir con el primer método solamente!

Casi he perdido mi fe en el jPowershell JAR externo. No obtengo el error en la segunda salida; pero, ni obtener la salida. ¡Se comporta como si no hubiera salida del comando!

¡Solicite amablemente ayudarme a resolver este problema!