WinSCP PowerShell脚本下载最新文件,但仅适用于与部分名称匹配的文件

rm5edbpk  于 2023-11-18  发布在  Shell
关注(0)|答案(1)|浏览(99)

我是这个WinSCP脚本的新手,但是,我试图找到一个脚本,可以下载最新的文件,但它只考虑符合部分名称标准的文件。
我找到了this script,但它下载的是最近的一个,但它占了文件夹中的所有文件。
任何帮助都是感激不尽的。

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
}

字符串

xxhby3vn

xxhby3vn1#

  • “Partial name criteria”* 有点模糊,但应该这样做:
$latest =
            $directoryInfo.Files |
            Where-Object { $_.Name -like "*partialname*" } |
            ...

字符串

相关问题