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.
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 }