将 FTP 上特定文件夹中的所有文件下载到本地文件夹

Download all files from specific folder on FTP to local folder

我正在尝试下载 FTP 站点上特定文件夹中的所有文件。该文件夹名为 "In"(如示例代码所示)并包含许多 .txt 文件。

当我 运行 下面的代码列出位于 FTP 文件夹 "ftp3.example.com/Jaz/In/" 中的四个 .txt 文件时,它不会将它们复制到 [= 的目标文件夹中14=]

注意:该列表会出现一瞬间,然后 PowerShell 会关闭。

请查看显示输出列表的屏幕截图

我已授予对 FTP 站点上的文件夹和内容的完全权限。

有人可以告诉我哪里错了吗?

$ftp = "ftp://ftp3.example.com/Jaz/In/" 
$user = 'username' 
$pass = 'password'
$folder = "/"
$target = 'C:\Users\Jasdeep\Destination'

$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()
}

$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, (Join-Path $target $file))

    $counter++
    $counter
    $source
}

提前致谢!

你的代码对我有用。但是 URL 中的斜线太多,所以可能您的特定服务器无法处理。

你的下载URL就像

ftp://ftp3.example.com/Jaz/In////test2.txt

将代码更改为:

$folderPath = "ftp://ftp3.example.com/Jaz/In/"

第二个问题是这样的:

$files = ($Allfiles -split "`r`n")

您依赖服务器 return 带有 CR+LF EOL 的列表。这是真的,只有当你让服务器使用 ASCII 模式时:

$request = [Net.WebRequest]::Create($url)
$request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
$request.UseBinary = $False

或者,作为特定于您的特定 FTP 服务器的快速破解,仅期望 LF:

$files = ($Allfiles -split "`n")

无论如何,"The list appears for a split second and then Powershell closes."说明你没有真正调试问题。 运行 来自现有 cmd.exe 或 PowerShell 控制台 window 的脚本,以查看其完整输出,包括任何错误。