Perfect! Thanks a lot dotps1!
- popotzo
Thanks dotps1! It's working now but the script is adding %5C in front of each file name.
Any idea or suggestion?
foreach ($file in $latest)
{
$session.GetFiles("$remotePath/$file", $localPath)
}
Param ( $localPath = 'c:\downloaded\', $remotePath = '/home/user/' )
try
{
# Load WinSCP .NET assembly
Add-Type -Path 'WinSCPnet.dll'
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
$sessionOptions.HostName = 'example.com'
$sessionOptions.UserName = 'user'
$sessionOptions.Password = 'mypassword'
$sessionOptions.SshHostKeyFingerprint = 'ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx'
$session = New-Object -TypeName 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 } | Sort-Object -Property LastWriteTime -Descending | Select-Object -First 12
# Any file at all?
if ($latest -eq $null)
{
Write-Output -InputObject "No file found"
exit 1
}
# Download the selected file
# $session.GetFiles($session.EscapeFileMask($remotePath + $latest.Name), $localPath).Check()
# Download list of files in foreach loop
foreach ($file in $latest)
{
$session.GetFiles("$remotePath/$file", $localPath)
}
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch [Exception]
{
Write-Error $_.Exception.Message
exit 1
}
$session.GetFiles($session.EscapeFileMask(/home/user/file1.txt file2.txt file3.text file4.txt), $localPath).Check()
Session.GetFiles
for each file in the collection. Are you doing this? Show us your complete code. A session log file would be useful too.