通过 Java 执行与 ADS 相关的 Powershell 命令不起作用 在使用 2 种不同的方式时出现 2 种不同的错误

executing ADS related Powershell command through Java does not work giving 2 different errors when using 2 different ways

我一直在尝试通过 java 在 powershell 会话中执行一组命令,但还没有成功。我的目标是在 AD 中搜索域为 "domain.com".

的计算机对象

我从一个命令开始。不幸的是,以下命令在我的 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 种不同的方法产生不同的 exceptions/errors。

  1. 我试过 ,然后将命令作为参数传递给它。这不起作用,导致如下所述的不同错误。

  2. 接下来,我再次尝试使用 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 有关,我对此经验不多。


编辑: Mathias R. Jessen's 回复后,第二种情况我没有收到任何错误;但是,图书馆本身似乎没有达到标准。

那么,关于第一种方法,我遇到了第一种情况中提到的错误。我只想继续使用第一种方法!

我几乎对外部 jPowershell JAR 失去了信心。我没有在第二个输出中得到错误;但是,都没有得到输出。它的行为就像没有命令的输出一样!

请求好心帮我解决这个问题!

折腾了将近3天,果不其然,发现问题出在命令字符串上。

正确的命令(对于第一种情况)应该是:

String firstPartCommand = "Get-ADComputer -Filter { Name -eq \'"+hostname+"\' } 
-Server a.b.c.d:3268 -SearchBase \'DC=domain,DC=com\' | Select DNSHostName";

正确的命令(对于第二种情况)应该是:

String firstPartCommand = "Get-ADComputer -Filter { Name -eq \'", 
secondPartCommand = "\' }  -Server a.b.c.d:3268 -SearchBase \'DC=domain,DC=com\' |
 Select DNSHostName";