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

时间:2015-11-20 20:53:03

标签: powershell ftp winscp winscp-net

我有一个调用WinSCP .NET程序集的脚本。该脚本从FTP目录下载最新文件,并根据文件扩展名+ .txt2245.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"} | 

谢谢!

1 个答案:

答案 0 :(得分:1)

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

  • -and具有“not directory”条件的扩展条件。或者使用两个单独的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
    }