Thank you, Martin. Very helpful as always.
Regards,
VtR
Regards,
VtR
Session.MoveFile
, not Session.MoveFiles
. And you need to use $transfer.FileName
. And Session.MoveFile
does not return anything.
$session.MoveFiles($transfer.FileName, $backupPath)
Session.MoveFiles
call should live. Any advice would be greatly appreciated. Code below.
param (
$localPath = "C:\upload\*",
$remotePath = "/home/user/",
$backupPath = "/home/archive/"
)
try
{
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "example.com"
UserName = "user"
Password = "mypassword"
SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
}
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Download files, collect results
$transferResult = $session.GetFiles($remotePath, $localPath)
# Iterate over every transfer
foreach ($transfer in $transferResult.Transfers)
{
# Success or error?
if ($transfer.Error -eq $Null)
{
Write-Host "Download of $($transfer.FileName) succeeded, moving to backup"
# Download succeeded, move source file to backup
# Move-Item $transfer.FileName $backupPath
$transferResult = $session.MoveFiles($remotePath, $backupPath)
}
else
{
Write-Host "Download of $($transfer.FileName) failed: $($transfer.Error.Message)"
}
}
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch
{
Write-Host "Error: $($_.Exception.Message)"
exit 1
}