title: Using PowerShell to download all files in a directory
body: <p>I have a working PowerShell script that iterates through a directory accessed via FTP and prints it's contents. The script looks like this:</p>
  
  <pre><code>$sourceuri = "&lt;string&gt;"
  $targetpath = "&lt;string&gt;"
  $username = "&lt;string&gt;"
  $password = "&lt;string&gt;"
  
  # Create a FTPWebRequest object to handle the connection to the ftp server
  $ftprequest = [System.Net.FtpWebRequest]::create($sourceuri)
  
  # set the request's network credentials for an authenticated connection
  $ftprequest.Credentials = New-Object System.Net.NetworkCredential($username,$password)
  
  $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
  $ftprequest.UseBinary = $true
  $ftprequest.KeepAlive = $false
  
  # send the ftp request to the server
  $ftpresponse = $ftprequest.GetResponse()
  $stream = $ftpresponse.getresponsestream()
  
  $buffer = new-object System.Byte[] 1024 
  $encoding = new-object System.Text.AsciiEncoding 
  
  $outputBuffer = "" 
  $foundMore = $false 
  
  ## Read all the data available from the stream, writing it to the 
  ## output buffer when done. 
  do 
  { 
      ## Allow data to buffer for a bit 
      start-sleep -m 1000 
  
      ## Read what data is available 
      $foundmore = $false 
      $stream.ReadTimeout = 1000 
  
      do 
      { 
          try 
          { 
              $read = $stream.Read($buffer, 0, 1024) 
              if($read -gt 0) 
              {
  
                  $foundmore = $true 
                  $outputBuffer += ($encoding.GetString($buffer, 0, $read)) 
              } 
          }
          catch
          { 
              $foundMore = $false; $read = 0 
          } 
      } 
      while($read -gt 0) 
  } 
  while($foundmore) 
  
  $outputBuffer 
  </code></pre>
  
  <p>My actual goal is not to just list the files but download them to the machine running the script. I'm finding this a bit tricky since my loops only reference bytes and not files by name. How can I use this loop to download all the files in a directory instead of just listing them?</p>