I'm trying to write a PowerShell WinSCP script to pull recently modified remote files from an SFTP server. WinSCP has a decent example in their documentation.
I'm really struggling though as Session.GetFiles is modifying the remote files timestamp to the current date. I've even tried EnumerateDirectory and doing a single GetFile for each file and it's doing the same thing. Oddly enough it does it on all the files on the remote server except a couple of them. But it defeats the entire purpose of the script because it ends up just downloading the same files over and over again since the lastwritetime gets updated on the remote file.
Is there some setting on the remote FTP server that when the file is accessed it updates the timestamp? My coworker was manually transferring the files recently and they all had their timestamps preserved so it would confound me if some kind of FTP setting was only affecting my script.
I've tried WinSCP 5.19.6 and 5.20 beta. Still the same issue.
I would greatly appreciate any insight.
Script is below:
# Set the last timestamp if exists
$TransferOptions = New-Object WinSCP.TransferOptions
if ($LastTimestamp -ne $Null) {
Write-Host "Downloading files modified after $LastTimestamp..."
$FileMask = "*>" + $LastTimestamp.ToString("yyyy-MM-dd HH:mm:ss")
Write-Host "FileMask: $FileMask"
$TransferOptions.FileMask = ($FileMask)
} else {
Write-Host "No timestamp found, downloading all files"
$FileMask = "| Aaaaa/; Bbbbbb/"
Write-Host "FileMask: $FileMask"
$TransferOptions.FileMask = ($FileMask)
}
# Perform the transfer
try {
$TransferResult = $Session.GetFiles("/", $LocalPath, $False, $TransferOptions)
$TransferResult.Check()
$LatestTransfer =
$TransferResult.Transfers |
Sort-Object -Property @{ Expression = { (Get-Item $_.Destination).LastWriteTime } } `
-Descending |
Select-Object -First 1
if ($LatestTransfer -eq $Null)
{
Write-Host "No newer files found."
}
else
{
$LastTimestamp = (Get-Item $latestTransfer.Destination).LastWriteTime
Write-Host (
"Downloaded $($transferResult.Transfers.Count) files, " +
"latest being $($latestTransfer.FileName) with timestamp $lastTimestamp.")
}
} catch {
Write-Error "Error downloading files, exiting without saving timestamp:"
Write-Error $_
exit
}
# Save the last timestamp
Set-Content -Path $TimestampFile -Value $LastTimestamp.ToString("O")