title: PsExec and Java to connect to a remote Windows Server
body: <p>I have a requirement where I need to connect to a Windows Server from another personal windows machine. I also need to be able to CD into a particular folder on the remote machine, get a list of files in that folder and check for the existence of a file in that folder. When I started researching about this, I could understand that there are two options:</p>
  
  <ul>
  <li>Have OpenSSH installed on the windows server and use clients like JSch to connect - my infra team may or may not approve this request.</li>
  <li>Use PsExec to connect and do a similar thing - here is where I am able to connect but not able to figure out how to CD to a directory and get a list of files in any folder there.</li>
  </ul>
  
  <p>Here is what I have in terms of code:</p>
  
  <pre><code>    private static void authenticateAndExecute() {
      String psCommand = PATH_TO_PSEXEC + "\\PsExec.exe \\\\" + "testdev19" + " -u " + "userName"
              + " -p " + "password";
      psCommand = psCommand + " " + "cmd cd c:\\destdir" + " dir ";
      String[] cmd = new String[5];
      cmd[0] = "cmd.exe";
      cmd[1] = "/C";
      cmd[2] = psCommand;
      cmd[3] = "";
      cmd[4] = "";
      // Run remote command
      Process p = null;
      try {
          p = Runtime.getRuntime().exec(cmd, null);
          System.out.println("Connected..." + p.getOutputStream());
          InputStream is = p.getInputStream();
  
          OutputStream os = p.getOutputStream();
  
          InputStream es = p.getErrorStream();
  
          BufferedReader reader = new BufferedReader(new InputStreamReader(is));
          BufferedReader errReader = new BufferedReader(new InputStreamReader(es));
          String line;
  
          // Read STDOUT into a buffer.
          while ((line = errReader.readLine()) != null) {
              System.out.println(line);
          }
          // If no STDOUT check STDERR.
          while ((line = reader.readLine()) != null) {
              System.out.println(line);
          }
          // Wait for the process to end.
      } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      } finally {
          if (p != null) {
              p.destroy();
          }
      }
  }
  </code></pre>
  
  <p>All I see after this is run is that the process has ended with a return code of 0. I want to see the list of files in the destination directory. Is this even possible using PsExec or am I going in the wrong path ?</p>
  
  <p>Any help is appreciated...</p>