Move files after upload using PowerShell/WinSCP Script

无人久伴 提交于 2021-02-08 10:35:14

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/48344586/move-files-after-upload-using-powershell-winscp-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!