Post a reply

Options
Add an Attachment

If you do not want to add an Attachment to your Post, please leave the Fields blank.

(maximum 10 MB; please compress large files; only common media, archive, text and programming file formats are allowed)

Options

Topic review

martin

Re: Automation Script Download Latest file and rename.

I'm not sure I understand. If you are asking how to download the latest file from the remote directory to a fixed local path (name), you can do:
$source = [WinSCP.RemotePath]::EscapeFileMask($latest.FullName)
$dest = (Join-Path $localPath $fileName)
$session.GetFiles($source, $dest).Check()
Bristow

Automation Script Download Latest file and rename.

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
}