简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM