title: Download most recent file from FTP using PowerShell
body: <p>I am working on a PowerShell script, which will pull files from an FTP site. The files are uploaded to the FTP site every hour so I need to download the most recent one. The code I currently have downloads all the files from today instead of just one file. How do I make it download only the most recent file?</p>
  
  <p>Here is the code that I am currently using</p>
  
  <pre><code>$ftpPath = 'ftp://***.***.*.*'
  $ftpUser = '******'
  $ftpPass = '******'
  $localPath = 'C:\Temp'
  $Date = get-date -Format "ddMMyyyy"
  $Files = 'File1', 'File2'
  
  function Get-FtpDir ($url, $credentials)
  {
    $request = [Net.FtpWebRequest]::Create($url)
    if ($credentials) { $request.Credentials = $credentials }
    $request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
    (New-Object IO.StreamReader $request.GetResponse().GetResponseStream()) -split "`r`n" 
  
  }
  
  $webclient = New-Object System.Net.WebClient 
  $webclient.Credentials = New-Object System.Net.NetworkCredential($ftpUser,$ftpPass)  
  $webclient.BaseAddress = $ftpPath
  
  Foreach ( $item in $Files )
  {
      Get-FTPDir $ftpPath $webclient.Credentials |
        ? { $_ -Like $item+$Date+'*' } |
        % {
  
            $webClient.DownloadFile($_, (Join-Path $localPath $_)) 
        }
  }
  </code></pre>