Automation Script Download Latest file and rename.

Advertisement

Bristow
Joined:
Posts:
1
Location:
UK

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
}

Reply with quote

Advertisement

martin
Site Admin
martin avatar
Joined:
Posts:
40,603
Location:
Prague, Czechia

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()

Reply with quote

Advertisement

You can post new topics in this forum