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
}
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
}