使用JAVA在远程计算机上运行PowerShell [英] Run a powershell on a remote machine using JAVA

查看:818
本文介绍了使用JAVA在远程计算机上运行PowerShell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用java在一些远程机器上运行powershell。
如何实现这一目标。
目前这段代码没有在本地运行powershell命令。!!

I want to run a powershell in some remote machine using java. How can this be achieved.? currently this code is not running the powershell command locally.!!

  public void main() throws Exception{

  String[] command = { /*"cmd.exe", "/C",*/ "powershell", "Command","&","echo '********** hello world ********'"};
  String out;

  ProcessBuilder processBuilder = new ProcessBuilder(command);

  Process process = null;

  try {
                            process = processBuilder.start();
                             Logger.getInstance().info("process started" );

                        } catch (IOException e2) {
                            // TODO Auto-generated catch block
                            e2.printStackTrace();
                        }


                        java.io.InputStream is = process.getInputStream();
                        InputStreamReader isr = new InputStreamReader(is);

                        BufferedReader br = new BufferedReader(isr);
                        // create a reader for the return data from cmd.
                        StringBuilder sb = new StringBuilder();
                        // create a string builder to automate the string addition

                        try {
                            while ((out = br.readLine()) != null) {// build the input
                                                                        // string from
                                                                        // cmd.

                                sb = sb.append(out);
                    System.out.println(out);

                            }


                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

此代码无限期运行。没有任何输出。

this code runs for indefinite time. without any output.

推荐答案

您可以尝试运行类似invoke-command -computername Server1 -filepath c:\ scripts的内容\ script.ps1

You can try to run something like "invoke-command -computername Server1 -filepath c:\scripts\script.ps1"

    Process p = new ProcessBuilder()
            .inheritIO()
            .command("invoke-command", "-computername", "Server1",
                    "-filepath", "C:\\scripts\\script.ps1").start();
    p.waitFor();

但首先要确保此命令在命令行中正常工作。

but first of all make sure that this command work OK from command line.

这篇关于使用JAVA在远程计算机上运行PowerShell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆