title: PowerShell readline from a stream
body: <p>Using a PowerShell script I will have to read and write to a console. We write an input and wait for an out that will be captured by <code>$Reader.ReadLine()</code>. But in some cases there wont be any output to get captured for the reader in that case the reader needs to look data from the stream and if there is no data the <code>ReadLine()</code> gets stuck/blocked waiting for the data from the console stream, whereas we need the <code>ReadLine()</code> to just wait for 5 seconds. If there is no data, it needs to get timed out and move on to the next command.</p>
  
  <p>Please let me know whether there is any way to timeout <code>$Reader.ReadLine()</code> in PowerShell?</p>
  
  <p>I see that in Java/C# we can use <code>$Reader.ReadLine(1000)</code> to timeout after 1 second but that doesn't seem to be working on PowerShell.</p>
  
  <pre><code>$tcpConnection = New-Object System.Net.Sockets.TcpClient($Computername, $Port)
  $tcpStream = $tcpConnection.GetStream()
  $reader = New-Object System.IO.StreamReader($tcpStream)
  $writer = New-Object System.IO.StreamWriter($tcpStream)
  $writer.AutoFlush = $true
  
  $buffer = New-Object System.Byte[] 1024
  $encoding = New-Object System.Text.AsciiEncoding 
  
  while ($tcpStream.DataAvailable) {
      $reader.ReadLine()
  }
  if ($tcpConnection.Connected) {
      $writer.WriteLine($username)
      $reader.ReadLine()
      $writer.WriteLine($password)
      $reader.ReadLine()
  
      try {
          # if there is any data it will show here if there is no data then
          # it should get timed out after 5 seconds
          $Reader.ReadLine()
      } catch {
          Write-Host "Login Failed"
      }
  }
  </code></pre>