title: How to connect to tcp socket with powershell to send and receive data?
body: <p>I have written a little Powershell script.</p>
  
  <p>It uses .Net System.IO.StreamReader and System.IO.StreamWriter to read and write data from/to the TCP socket.</p>
  
  <p>I would like to connect to a socket telnet style with it and send/receive commands.</p>
  
  <p>I am trying to read the lines with the ReadLine() method from the System.IO.StreamReader but the data from the server maybe does not arrive in time(?) or IDK. I am not using async commands. Please help me with that!</p>
  
  <p>Here is my script:</p>
  
  <pre><code>$FTPServer = "localhost"
  $FTPPort = "21"
  
  $tcpConnection = New-Object System.Net.Sockets.TcpClient($FTPServer, $FTPPort)
  $tcpStream = $tcpConnection.GetStream()
  $reader = New-Object System.IO.StreamReader($tcpStream)
  $writer = New-Object System.IO.StreamWriter($tcpStream)
  $writer.AutoFlush = $true
  
  while ($tcpConnection.Connected)
  {
      while ($tcpStream.DataAvailable)
      {
          $reader.ReadLine()
      }
  
      if ($tcpConnection.Connected)
      {
          Write-Host -NoNewline "prompt&gt; "
          $command = Read-Host
  
          if ($command -eq "escape")
          {
              break
          }
  
          $writer.WriteLine($command) | Out-Null
      }
  }
  
  $reader.Close()
  $writer.Close()
  $tcpConnection.Close()
  </code></pre>
  
  <p>And here is the output:</p>
  
  <pre><code>PS C:\Windows\System32\WindowsPowerShell\v1.0&gt; test.ps1
  220 Microsoft FTP Service
  prompt&gt; user username
  331 Password required
  prompt&gt; pass password
  230-Directory has 58,145,996,800 bytes of disk space available.
  prompt&gt; 
  230 User logged in.
  500 Command not understood.
  prompt&gt; help
  214-The following commands are recognized (* ==&gt;'s unimplemented).
      ABOR 
      ACCT 
      ADAT *
      ALLO 
      APPE 
      AUTH 
      CCC 
      CDUP 
      CWD 
      DELE 
      ENC *
      EPRT 
      EPSV 
      FEAT 
      HELP 
      HOST 
      LANG 
      LIST 
      MDTM 
      MIC *
      MKD 
      MODE 
      NLST 
      NOOP 
      OPTS 
      PASS 
      PASV 
      PBSZ 
      PORT 
      PROT 
      PWD 
      QUIT 
      REIN 
      REST 
      RETR 
      RMD 
      RNFR 
      RNTO 
      SITE 
  prompt&gt; escape
  
  PS C:\Windows\System32\WindowsPowerShell\v1.0&gt;
  </code></pre>