This is not easy with FtpWebRequest . For your task you need to know the timestamps of the file.
Unfortunately, there is no reliable and efficient way to get timestamps using the functions offered by the FtpWebRequest /.NET framework / PowerShell, because they do not support the FTP MLSD . The MLSD team provides a list of remote directories in a standard machine-readable format. Command and format are standardized by RFC 3659 .
Alternatives you can use that are supported by the .NET platform:
ListDirectoryDetails method (FTP LIST command) to get information about all the files in the directory, and then you are dealing with a specific FTP server data format (the * nix format, similar to the ls * nix ls , is the most common drawback is that the format can change over time, because the format "May 8 17:48" is used for older files, and the format "October 18, 2009" is used for older files).GetDateTimestamp method (FTP MDTM ) for individually obtaining timestamps for each file. The advantage is that the response is standardized by RFC 3659 to YYYYMMDDHHMMSS[.sss] . The downside is that you need to send a separate request for each file, which can be quite inefficient.
Some links:
Alternatively, use a third-party FTP library that supports the MLSD command and / or supports listing listing format analysis.
For example, WinSCP.NET assembly supports both.
Code example:
# Load WinSCP .NET assembly Add-Type -Path "WinSCPnet.dll" # Setup session options $sessionOptions = New-Object WinSCP.SessionOptions -Property @{ Protocol = [WinSCP.Protocol]::Ftp HostName = "example.com" UserName = "user" Password = "mypassword" } $session = New-Object WinSCP.Session # Connect $session.Open($sessionOptions) # Get list of files in the directory $directoryInfo = $session.ListDirectory($remotePath) # Select the most recent file $latest = $directoryInfo.Files | Where-Object { -Not $_.IsDirectory } | Sort-Object LastWriteTime -Descending | Select-Object -First 1 # Any file at all? if ($latest -eq $Null) { Write-Host "No file found" exit 1 } # Download the selected file $sourcePath = [WinSCP.RemotePath]::EscapeFileMask($remotePath + $latest.Name) $session.GetFiles($sourcePath, $localPath).Check()
For complete code, see Download the latest file (PowerShell) .
(I am the author of WinSCP)
source share