Hi
I'm using the below script but can not work out how to rename the file once downloaded. I'm trying to download the latest file from a SFTP site and then rename it to a generic name and copy to a local directory overwriting the previous days file.
Any help would be much appreciated.
param (
$localPath = "C:\downloads\",
$remotePath = "/Test",
$fileName = "TestFile.xlsx"
)
try
{
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "My server.co.uk"
PortNumber = 22
UserName = "Test"
Password = "Test"
SshHostKeyFingerprint = "ssh-rsa 2048 TEST="
}
$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
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch
{
Write-Host "Error: $($_.Exception.Message)"
exit 1
}