我有一个调用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"} |
谢谢!
答案 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
}