title: run PowerShell command remotely using Java
body: <p>I want to run a PowerShell command using Java on a remote windows machine, which is actually to open the inbound firewall port. <em>script.ps1</em> contains the below command</p>
  
  <blockquote>
    <p>PowerShell cmd:-  <strong>netsh advfirewall firewall add rule name="Open Port
    (8077)" dir=in action=allow protocol=TCP localport=(8077)</strong></p>
  </blockquote>
  
  <p><a href="https://i.stack.imgur.com/GMdgz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GMdgz.png" alt="enter image description here"></a></p>
  
  <p>The below code works fine locally. But I want to do same on a remote machine from my local machine only and I can't do anything manually (not even creating a ps1 file over there). I have admin rights on the remote computer.</p>
  
  <pre><code>import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStreamReader;
  
  public class TestMain2 {
  
      public static void main(String[] args) throws IOException {
          String command = "powershell.exe \"C:\\Users\\Administrator\\Desktop\\agent_port\\script.ps1\"";
  
          // Executing the command
          Process powerShellProcess = Runtime.getRuntime().exec(command);
          // Getting the results
          powerShellProcess.getOutputStream().close();
          String line;
          System.out.println("Standard Output:");
          BufferedReader stdout = new BufferedReader(new InputStreamReader(powerShellProcess.getInputStream()));
          while ((line = stdout.readLine()) != null) {
              System.out.println(line);
          }
          stdout.close();
          System.out.println("Standard Error:");
          BufferedReader stderr = new BufferedReader(new InputStreamReader(powerShellProcess.getErrorStream()));
          while ((line = stderr.readLine()) != null) {
              System.out.println(line);
          }
          stderr.close();
          System.out.println("Done");
  
      }
  }
  </code></pre>
  
  <p>I tried this link also :- <a href="https://stackoverflow.com/questions/40351357/running-powershell-script-remotely-through-java">Running Powershell script remotely through Java</a></p>