PowerShell FTP下载文件和子文件夹

Pas*_*cal 7 ftp powershell download subdirectory

我喜欢编写一个PowerShell脚本来从我的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")

$files 

$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 = $target + $file 
    $webclient.DownloadFile($source, $target+$file)

    #PRINT FILE NAME AND COUNTER
    $counter++
    $counter
    $source
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助 (:

Mar*_*ryl 5

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

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

棘手的部分是从子目录中识别文件。.NET框架(FtpWebRequestWebClient)无法以可移植的方式进行操作。不幸的是,.NET框架不支持该MLSD命令,这是使用FTP协议检索具有文件属性的目录列表的唯一可移植方式。另请参阅检查FTP服务器上的对象是文件还是目录

您的选择是:

  • 对一定要对文件失败但对目录成功的文件名执行操作(反之亦然)。即,您可以尝试下载“名称”。如果成功,则为文件;如果失败,则为目录。
  • 您可能很幸运,在您的特定情况下,您可以通过文件名告诉目录中的文件(即,所有文件都有扩展名,而子目录则没有)
  • 您使用长目录列表(LISTcommand = ListDirectoryDetailsmethod)并尝试解析服务器特定的列表。许多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()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

使用如下功能:

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

代码是从C#中的C#示例转换而来的。通过FTP下载所有文件和子目录

尽管Microsoft不建议FtpWebRequest进行新的开发


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

例如,使用WinSCP .NET程序集,您只需一次调用即可下载整个目录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()
}    
Run Code Online (Sandbox Code Playgroud)

MLSD如果服务器支持,WinSCP在内部使用该命令。如果没有,它将使用该LIST命令并支持多种不同的列表格式。

默认情况下,该Session.GetFiles方法是递归的。

(我是WinSCP的作者)

  • 非常感谢。与 winscp 完美配合! (2认同)