Jmmitche1984
Jmmitche1984

Reputation: 11

Move files after upload using PowerShell/WinSCP Script

I am using a PowerShell script generated in WinSCP to sftp files in a certain folder. It runs every Friday morning, but I need it to move the files to another folder after they are uploaded. I tried the MoveFiles and PutFiles command but they don't seem to work. Any help is appreciated. Code below.

# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"

# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Sftp
    HostName = "xxxx"
    UserName = "xxxxx"
    Password = "xxxx"
    SshHostKeyFingerprint = "xxxxx"
}

$session = New-Object WinSCP.Session

try
{
    # Connect
    $session.Open($sessionOptions)

    # Transfer files
    $session.PutFiles("xxxxx", "xxxxxx*").Check()


}
finally
{
    $session.Dispose()
}

Upvotes: 0

Views: 2706

Answers (2)

Rudemaniac
Rudemaniac

Reputation: 1

Yes, I did see this on Google. This issue I am having is when you have multiple lines in the section below:

# Transfer files
$session.PutFiles("xxxxx", "xxxxxx*").Check()

It does not seem to go line by line after the transfer and move each file after the transfer. It only moved the first file in the list.

Upvotes: 0

Martin Prikryl
Martin Prikryl

Reputation: 202158

There's an example on WinSCP site example for your exact question:
Moving local files to different location after successful upload.

It happens to be the very first google hit for your question title!


The relevant piece of the code is:

# Iterate over every transfer
foreach ($transfer in $transferResult.Transfers)
{
    # Success or error?
    if ($transfer.Error -eq $Null)
    {
        Write-Host "Upload of $($transfer.FileName) succeeded, moving to backup"
        # Upload succeeded, move source file to backup
        Move-Item $transfer.FileName $backupPath
    }
    else
    {
        Write-Host "Upload of $($transfer.FileName) failed: $($transfer.Error.Message)"
    }
}

Upvotes: 1

Related Questions