phantom2000
Tried it myself, used the $ftprequest.Method=[system.net.WebRequestMethods+ftp]::ListDirectoryDetails to get timestamps but not easy to parse those. Then I read a post (https://stackoverflow.com/questions/40845688/download-most-recent-file-from-ftp-using-powershell) about using WinSCP as client which gives you more options. Also a link below in the same article with even more code https://winscp.net/eng/docs/script_download_most_recent_file
# 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()
This piece of code was written by the author of WinSCP (Martin Prikryl ) , so I know it's good 🙂