我需要修改我的 WinSCP 脚本以仅下载特定文件扩展名的文件

I need to modify my WinSCP script to only download files of specific file extensions

我有一个调用 WinSCP .NET 程序集的脚本。该脚本从 FTP 目录下载最新文件,并根据文件扩展名 + .txt (2245.xml -> xml.txt).

命名它们

我需要创建一个过滤器以仅下载名为 tn*nc1 的文件扩展名。谁能指出我正确的方向:

$session = New-Object WinSCP.Session

# 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} | 
    Group-Object { [System.IO.Path]::GetExtension($_.Name) } | 
    ForEach-Object{ 
        $_.Group | Sort-Object LastWriteTime -Descending | Select -First 1
    }

$extension = [System.IO.Path]::GetExtension($latest.Name)
"GetExtension('{0}') returns '{1}'" -f $fileName, $extension

if ($latest -eq $Null)
{
    Write-Host "No file found"
    exit 1
}

# Download

$latest | ForEach-Object {
    $extension = ([System.IO.Path]::GetExtension($_.Name)).Trim(".")
    $session.GetFiles($session.EscapeFileMask($remotePath + $_.Name), "$localPath$extension.txt" ).Check()
}

我尝试在目录排序中添加过滤器,但没有用:

    Where-Object { -Not $_.IsDirectory -or [System.IO.Path]::GetExtension($_.Name) -like "tn*" -or [System.IO.Path]::GetExtension($_.Name) -eq "nc1"} | 

谢谢!

您的代码几乎是正确的。只需要:

  • -and 带有“非目录”条件的扩展条件。或者像我下面那样使用两个单独的 Where-Object 子句。
  • GetExtension 结果包含点。
$latest = $directoryInfo.Files |
    Where-Object { -Not $_.IsDirectory } | 
    Where-Object {
        [System.IO.Path]::GetExtension($_.Name) -eq ".nc1" -or
        [System.IO.Path]::GetExtension($_.Name) -like ".tn*"
    } |
    Group-Object { [System.IO.Path]::GetExtension($_.Name) } | 
    ForEach-Object { 
        $_.Group | Sort-Object LastWriteTime -Descending | Select -First 1
    }