且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从FTP服务器上的通配符文件夹中自动下载特定文件类型

更新时间:2023-02-08 18:40:07

选择要传输的文件时,文件掩码只能用于路径的最后一部分.

When selecting files to transfer, file mask can be used for the last component of the path only.

您可以做的一件事是:

get -filemask=*.mkv /The.Walking.Dead.* "E:\Torrents\TV Shows\The Walking Dead\Season 8\"

但这将重新创建匹配的文件夹( The.Walking.Dead.* )作为目标本地文件夹( Season 8 )的子文件夹.

But this will re-create the matching folder (The.Walking.Dead.*) as a subfolder of the target local folder (Season 8).

如果要直接将文件( *.mkv )下载到目标本地文件夹( Season 8 ),则可以使WinSCP重命名"源文件夹转到第8季:

If you want to download the files (*.mkv) directly to the target local folder (Season 8), you can make WinSCP "rename" the source folder to Season 8:

get -filemask=*.mkv /The.Walking.Dead.* "E:\Torrents\TV Shows\The Walking Dead\Season 8"

请注意目标路径中没有尾随反斜杠.它使WinSCP将匹配的源文件夹( The.Walking.Dead.* )下载到目标本地文件夹( The Walking Dead ,而不是 Season 8 >!),名称为 Season 8 .由于 Season 8 已经存在,它不会执行任何操作,并将直接继续下载包含的文件.

Note the absence of the trailing backslash in the target path. It makes WinSCP download the matching source folder (The.Walking.Dead.*) to the target local folder (The Walking Dead, not Season 8!) under a name Season 8. As Season 8 already exists, it won't do anything with it and will directly continue with downloading the contained files.

前面的内容适用于您的特定情况.在更复杂的情况下,您需要在下载之前找出文件夹的名称.虽然使用普通的批处理文件来实现它不是不可能的,但是这将非常复杂.

The previous works for your specific case. In more complex cases, you would need to find out the name of the folder before the download. While it is not impossible to implement this using a plain batch file, it would be very complicated.

在这种情况下,我建议使用 WinSCP .NET程序集使用PowerShell.

In such case, I would suggest using PowerShell with use of WinSCP .NET assembly.

有了它,脚本(例如 download.ps1 )将类似于:

With it, the script (e.g. download.ps1) would be like:

# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Ftp
    HostName = "ftp.example.com"
    UserName = "username"
    Password = "password"
}

Write-Host "Connecting..."
$session = New-Object WinSCP.Session
$session.SessionLogPath = "session.log"
$session.Open($sessionOptions)

$remotePath = "/"
$localPath = "C:\local\path"
$pattern = "The.Walking.Dead.*"
$twdFolder =
    $session.ListDirectory($remotePath).Files |
    Where-Object { $_.IsDirectory -and ($_.Name -like $pattern) } |
    Select-Object -First 1

if ($twdFolder -eq $Null)
{
    Write-Host "No folder matching '$pattern' found."
}
else
{
    Write-Host "Found folder '$($twdFolder.Name)', downloading..."
    $sourcePath = [WinSCP.RemotePath]::Combine($remotePath, $twdFolder.Name)
    $sourcePath = [WinSCP.RemotePath]::Combine($sourcePath, "*")
    $destPath = Join-Path $localPath "*"
    $transferResult = $session.GetFiles($sourcePath, $destPath).Check()
}

Write-Host "Done"

提取WinSCP自动化程序包以及脚本和 查看全文