Files downloading but not being removed from the server

Advertisement

Starek
Joined:
Posts:
1
Location:
United Kingdom

Files downloading but not being removed from the server

Hi guys,
I'm trying to automate downloading files (without sub folders) from SFTP server and then removing them from that server. Can anyone help in achieving that?
I have run multiple scripts now but none of them are doing what they should.
The only one working I got is this, but it downloads only latest file, and for some reason the file is not being removed from the server.
param (
    $localPath = "c:\frlsageexport",
    $remotePath = "/"
)
 
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 = "sftp@sftp.com"
        UserName = "xyz"
        Password = "xyz"
        SshHostKeyFingerprint = "xyzxyzxyz"
    }
 
    $sessionOptions.AddRawSettings("FSProtocol", "2")
 
    $session = New-Object WinSCP.Session
 
    try
    {
        # Connect
        $session.Open($sessionOptions)
 
        # Get list of files in the directory
        $directoryInfo = $session.ListDirectory($remotePath)
 
        # Select the most recent file
        $latest =
            $directoryInfo.Files |
            Where-Object { -Not $_.IsDirectory } |
            Sort-Object LastWriteTime -Descending |
            Select-Object -First 1
 
        # Any file at all?
        if ($latest -eq $Null)
        {
            Write-Host "No file found"
            exit 1
        }
 
        # Download the selected file
        $session.GetFileToDirectory($latest.FullName, $localPath) | Out-Null
 
        $Directory = $session.ListDirectory("/")
        foreach ($FileInfo in $Directory.Files)
        {
            $RemovalFile = ($FileInfo.Name)
            $session.RemoveFiles($RemovalFile)
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
 
    exit 0
}
catch
{
    Write-Host "Error: $($_.Exception.Message)"
    exit 1
}

Reply with quote

Advertisement

martin
Site Admin
martin avatar
Joined:
Posts:
41,440
Location:
Prague, Czechia

Re: Files downloading but not being removed from the server

Downloading files from a folder, but not subfolders, and then deleting them, should be as easy as:
$options = New-Object WinSCP.TransferOptions -Property @{ FileMask = "| */" }
$delete = $True
 
$session.GetFilesToDirectory(
    $remotePath, $localPath, $Null, $delete, $options).Check()
See How do I transfer (or synchronize) directory non-recursively?

Reply with quote

Advertisement

You can post new topics in this forum