Post a reply

Options
Add an Attachment

If you do not want to add an Attachment to your Post, please leave the Fields blank.

(maximum 10 MB; please compress large files; only common media, archive, text and programming file formats are allowed)

Options

Topic review

martin

Re: Search recursively download most recent file

Show us your complete code.
Guest

Re: Search recursively download most recent file

martin wrote:

Instead of using $session.ListDirectory($remotePath).Files, use $ession.EnumerateRemoteFiles($remotePath, "*", [WinSCP.EnumerationOptions]::AllDirectories) (5.8.3 RC version only)
https://winscp.net/eng/docs/library_session_enumerateremotefiles


I have changed
# Get list of files in the directory
$directoryInfo = $session.ListDirectory($remotePath)

Into
# Get list of files in the directory
$session.EnumerateRemoteFiles($remotePath, "*", [WinSCP.EnumerationOptions]::AllDirectories)

It does not generate an error anymore but does not download a file either.
There are two files on the remote location.
Partridge

Anyone?
Partridge

Search recursively download most recent file

I want to make a connection to an SFTP server and download the latest zip-file.
The remote path consists of several directories which contains zip-files.
At the moment the script only downloads zip-files from /Output
But I also want to check the subfolders for example /Output/Work1

How can I accomplish this? see code below:


param (
$localPath = "D:\temp\",
$remotePath = "/Output/"
)

try
{
# Load WinSCP .NET assembly
Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"

# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "myhost"
UserName = "user"
Password = "password"
SshHostKeyFingerprint = "ssh-rsa 2048 xxx xxx xxx xxx"
}

$session = New-Object WinSCP.Session

try
{
# 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 } |
#$directoryInfo.Files |
#get-childitem -Recurse | Where-Object {$_.Extension -eq ".zip"} |
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
$session.GetFiles($session.EscapeFileMask($remotePath + $latest.Name), $localPath).Check()
}
finally
{
# Disconnect, clean up
$session.Dispose()
}

exit 0
}
catch [Exception]
{
Write-Host ("Error: {0}" -f $_.Exception.Message)
exit 1
}