且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 Java 程序内部创建 powershell 远程会话?

更新时间:2021-09-07 04:08:08

看这里面涉及到很多逻辑可以帮到你.

See there are lot of logics involves in this which can help you.

你的会话调用没问题;但是你不能直接运行这样的 PS 命令.您必须首先调用 powershell.exe,然后您必须向相应的远程命令提供您想要执行的内容.

Your session invoking is fine; But you cannot directly run a PS command like that. You have to invoke the powershell.exe first then you have to give the respective remote commands what you want to execute.

最后,您已执行将要准备的命令.让我与您分享一个示例代码:

Finally you have execute the command you will prepare. Let me share you a sample code:

public String executeScript(String psFileName, Systems system) throws NMAException {

        Runtime runtime = Runtime.getRuntime();
        String filePath = ApplicationProperties.getPropertyValue("powershell.scripts.location");
        String command;

        switch (psFileName) {
            case "TerminalServersSystemInfo.ps1":
                command = POWERSHELL + filePath + psFileName + " " + system.getPassword() + " " + system.getUserName()
                        + " " + system.getSystemName();
                break;
            case "SQLServerInfo.ps1":
                command = POWERSHELL + filePath + psFileName + " " + system.getSystemName() + " "
                        + system.getUserName() + " " + system.getPassword();
                break;
            case "MyPS.ps1":

            {
                command = POWERSHELL + filePath + psFileName + " " + system.getSystemName() + " "
                        + system.getUserName()
                        + " " + system.getPassword() + " " + system.getDatabaseName();
                break;
            }

            default:
                throw new NMAException("not available");
        }

这里是你应该如何在 Java 中形成命令对象,然后你应该执行这个:

Here is how you should form the command object in Java and then you should execute this:

powershell -ExecutionPolicy Bypass -NoLogo -NoProfile -Command {Invoke-command ......}

要触发 PS 文件,您可以使用 -Filepath 开关.

For triggering a PS file you can use the -Filepath switch.

接下来这将帮助您执行该操作:

Next this will help you in executing that:

proc = runtime.exec(command);
            proc.getOutputStream().close();
            InputStream is = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader reader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            reader.close();
            proc.getOutputStream().close();
            LOGGER.info("Command: " + command);
            LOGGER.info("Result:" + sb.toString());
            return sb.toString();

希望它能让你有所收获.

Hope it gives you a set off.