PowerShell FTP 下载文件和子文件夹

2024-05-20

我喜欢写一个PowerShell脚本来下载全部文件 and 子文件夹从我的 FTP 服务器。我找到了一个脚本来下载一个特定文件夹中的所有文件,但我也喜欢下载子文件夹及其文件。

#FTP Server Information - SET VARIABLES
$ftp = "ftp://ftp.abc.ch/" 
$user = 'abc' 
$pass = 'abc'
$folder = '/'
$target = "C:\LocalData\Powershell"

#SET CREDENTIALS
$credentials = new-object System.Net.NetworkCredential($user, $pass)

function Get-FtpDir ($url,$credentials) {
    $request = [Net.WebRequest]::Create($url)
    $request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
    if ($credentials) { $request.Credentials = $credentials }
    $response = $request.GetResponse()
    $reader = New-Object IO.StreamReader $response.GetResponseStream() 
    $reader.ReadToEnd()
    $reader.Close()
    $response.Close()
}

#SET FOLDER PATH
$folderPath= $ftp + "/" + $folder + "/"

$Allfiles=Get-FTPDir -url $folderPath -credentials $credentials
$files = ($Allfiles -split "`r`n")

$webclient = New-Object System.Net.WebClient 
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass) 
$counter = 0
foreach ($file in ($files | where {$_ -like "*.*"})){
    $source=$folderPath + $file  
    $destination = Join-Path $target $file 
    $webclient.DownloadFile($source, $destination)

    #PRINT FILE NAME AND COUNTER
    $counter++
    $counter
    $source
}

感谢您的帮助 (:


.NET 框架或 PowerShell 对递归文件操作(包括下载)没有任何显式支持。您必须自己实现递归:

  • 列出远程目录
  • 迭代条目,下载文件并递归到子目录(再次列出它们等)

棘手的部分是识别子目录中的文件。 .NET 框架无法以可移植的方式做到这一点(FtpWebRequest or WebClient)。不幸的是.NET框架不支持MLSD命令,这是在 FTP 协议中检索带有文件属性的目录列表的唯一可移植方法。也可以看看检查 FTP 服务器上的对象是文件还是目录 https://stackoverflow.com/q/36895021/850848.

您的选择是:

  • 对文件名执行的操作对于文件肯定会失败,而对于目录则成功(反之亦然)。 IE。你可以尝试下载“名字”。如果成功,它是一个文件,如果失败,它是一个目录。
  • 您可能很幸运,在您的特定情况下,您可以通过文件名区分文件和目录(即所有文件都有扩展名,而子目录没有)
  • 您使用长目录列表(LIST命令=ListDirectoryDetails方法)并尝试解析特定于服务器的列表。许多 FTP 服务器使用 *nix 样式的列表,您可以通过d在条目的最开始。但许多服务器使用不同的格式。以下示例使用此方法(假设为 *nix 格式)
function DownloadFtpDirectory($url, $credentials, $localPath)
{
    $listRequest = [Net.WebRequest]::Create($url)
    $listRequest.Method =
        [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
    $listRequest.Credentials = $credentials
    
    $lines = New-Object System.Collections.ArrayList

    $listResponse = $listRequest.GetResponse()
    $listStream = $listResponse.GetResponseStream()
    $listReader = New-Object System.IO.StreamReader($listStream)
    while (!$listReader.EndOfStream)
    {
        $line = $listReader.ReadLine()
        $lines.Add($line) | Out-Null
    }
    $listReader.Dispose()
    $listStream.Dispose()
    $listResponse.Dispose()

    foreach ($line in $lines)
    {
        $tokens = $line.Split(" ", 9, [StringSplitOptions]::RemoveEmptyEntries)
        $name = $tokens[8]
        $permissions = $tokens[0]

        $localFilePath = Join-Path $localPath $name
        $fileUrl = ($url + $name)

        if ($permissions[0] -eq 'd')
        {
            if (!(Test-Path $localFilePath -PathType container))
            {
                Write-Host "Creating directory $localFilePath"
                New-Item $localFilePath -Type directory | Out-Null
            }

            DownloadFtpDirectory ($fileUrl + "/") $credentials $localFilePath
        }
        else
        {
            Write-Host "Downloading $fileUrl to $localFilePath"

            $downloadRequest = [Net.WebRequest]::Create($fileUrl)
            $downloadRequest.Method =
                [System.Net.WebRequestMethods+Ftp]::DownloadFile
            $downloadRequest.Credentials = $credentials

            $downloadResponse = $downloadRequest.GetResponse()
            $sourceStream = $downloadResponse.GetResponseStream()
            $targetStream = [System.IO.File]::Create($localFilePath)
            $buffer = New-Object byte[] 10240
            while (($read = $sourceStream.Read($buffer, 0, $buffer.Length)) -gt 0)
            {
                $targetStream.Write($buffer, 0, $read);
            }
            $targetStream.Dispose()
            $sourceStream.Dispose()
            $downloadResponse.Dispose()
        }
    }
}

使用如下函数:

$credentials = New-Object System.Net.NetworkCredential("user", "mypassword") 
$url = "ftp://ftp.example.com/directory/to/download/"
DownloadFtpDirectory $url $credentials "C:\target\directory"

该代码是从我的 C# 示例翻译而来的C# 通过FTP下载所有文件及子目录 https://stackoverflow.com/q/37038676/850848.

Though 微软不推荐FtpWebRequest为了新的发展 https://github.com/dotnet/platform-compat/blob/master/docs/DE0003.md.


如果您想避免解析特定于服务器的目录列表格式的麻烦,请使用支持MLSD命令和/或解析各种LIST列表格式;和递归下载。

例如与WinSCP .NET 程序集 https://winscp.net/eng/docs/library您只需调用一次即可下载整个目录Session.GetFiles https://winscp.net/eng/docs/library_session_getfiles:

# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"

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

$session = New-Object WinSCP.Session

try
{
    # Connect
    $session.Open($sessionOptions)

    # Download files
    $session.GetFiles("/directory/to/download/*", "C:\target\directory\*").Check()
}
finally
{
    # Disconnect, clean up
    $session.Dispose()
}    

在内部,WinSCP 使用MLSD命令(如果服务器支持)。如果没有,则使用LIST命令并支持数十种不同的列表格式。

The Session.GetFiles method https://winscp.net/eng/docs/library_session_getfiles默认是递归的。

(我是WinSCP的作者)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PowerShell FTP 下载文件和子文件夹 的相关文章

随机推荐