Monty
Monty

Reputation: 35

Remove files from FTP after transfer Powershell WinSCP

I have previously using .bat scripts for this process and am relatively new to writing powershell scripts. I am conducting a transfer from an FTP location and need to delete each file from the FTP server after transfer. What is the correct syntax for this? Code is as follows:-

$a=Get-Date -format MMMM
try
{
    # Load WinSCP .NET assembly
    Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"

    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "xxx.xxx.xxx.xxx"
        UserName = "joe"
        Password = "joebloggs"
        SshHostKeyFingerprint = "ssh-rsa 1024 01:07:da:11:22:33:44:55:66"
        FtpMode = [WinSCP.FtpMode]::Active
    }

    $session = New-Object WinSCP.Session

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

        # Download files
        $transferOptions = New-Object WinSCP.TransferOptions
        $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary

        $transferResult = $session.GetFiles("/*", "C:\Users\User\Dropbox\Rockar\Data\System Data\Raw Feeds\Stock\"+$a+"\", $False, $transferOptions)

        # Throw on any error
        $transferResult.Check()

        # Print results
        foreach ($transfer in $transferResult.Transfers)
        {
            Write-Host ("Download of {0} succeeded" -f $transfer.FileName)
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }

Upvotes: 0

Views: 3321

Answers (2)

Monty
Monty

Reputation: 35

Discovered the answer with a bit of further reading on the WinSCP site about getfiles parameters winscp.net/eng/docs/library_session_getfiles#parameters the remove parameter just needs setting to $true from $false

Upvotes: 2

Andrey Marchuk
Andrey Marchuk

Reputation: 13483

You should call $session.RemoveFiles, here's the method description: https://winscp.net/eng/docs/library_session_removefiles

Upvotes: 0

Related Questions