WinSCP PowerShell script to download most recent file but only for files matching a partial name

103 Views Asked by At

I'm new to this WinSCP scripting, however, I'm trying to find a script that would download the most recent file, but it only account for files that match a partial name criteria.

I found this script, but it downloads the most recent one, but it accounts for all files in the folder.

Any help is appreciated.

param (
    $localPath = "c:\downloaded",
    $remotePath = "/home/user"
)
 
try
{
    # Load WinSCP .NET assembly
    Add-Type -Path "WinSCPnet.dll"
 
    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "example.com"
        UserName = "user"
        Password = "mypassword"
        SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..."
    }
 
    $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
}
1

There are 1 best solutions below

0
On

"Partial name criteria" is bit vague, but something like this should do:

        $latest =
            $directoryInfo.Files |
            Where-Object { $_.Name -like "*partialname*" } |
            ...