We are using a PowerShell script that is downloading documents from an SFTP server. This was running for quite a long time without any issue, but recently we are running into sporadic error code 2 stating, the file does not exist...? Any idea what could be the issue here?
param([string] $hostname,
[string] $username,
[string] $password,
[string] $source,
[string] $destination
)
# Set log file
$scriptname = ([System.IO.FileInfo]$MyInvocation.MyCommand.Definition).BaseName
$logfile = "$PSScriptRoot\$scriptname.log"
# Log function
Function LogWrite
{
param([string] $logstring)
Add-Content $logfile -value $logstring
}
try
{
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = $hostname
PortNumber = 2222
UserName = $username
Password = $password
SshHostKeyFingerprint = "*******"
}
# Create session
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Find files older than 3 minutes
$directoryInfo = $session.ListDirectory($source)
$limit = (Get-Date).AddMinutes(-5)
$readyFiles =
$directoryInfo.Files |
Where-Object { -Not $_.IsDirectory } |
Where-Object { $_.LastWriteTime -lt $limit }
# Set transfer options
$transferOptions = New-Object WinSCP.TransferOptions
$transferOptions.TransferMode = [WinSCP.TransferMode]::Binary
$transferOptions.OverwriteMode = [WinSCP.OverwriteMode]::Overwrite
foreach ($readyFile in $readyFiles)
{
# Download files
$transferResult = $session.GetFiles($session.EscapeFileMask($source + "/" + $readyFile.Name), $destination, $True, $transferOptions)
# Throw on any download error
$transferResult.Check()
# Log download results
foreach ($transfer in $transferResult.Transfers)
{
LogWrite ("{0}: Download of {1} succeeded" -f (Get-Date), $transfer.FileName)
}
}
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch [Exception]
{
LogWrite ("{0}: {1}" -f (Get-Date), $_.Exception.Message)
exit 1
}