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

.net 将FTP上特定文件夹中的所有文件下载到本地文件夹,.net,powershell,ftp,ftpwebrequest,.net,Powershell,Ftp,Ftpwebrequest,我正在尝试下载FTP站点上特定文件夹中的所有文件。该文件夹在“”中称为“”(如示例代码所示),其中包含许多.txt文件 当我运行下面的代码时,它列出了FTP文件夹“ftp3.example.com/Jaz/in/”中的四个.txt文件,但是它不会将它们复制到“C:\Users\Jasdeep\Destination\”的目标文件夹中 注意:该列表会在瞬间显示,然后PowerShell关闭 请参阅显示输出列表的屏幕截图 我已授予FTP站点上的文件夹和内容的完全权限 有人能告诉我哪里出了问题吗 $

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

当我运行下面的代码时,它列出了FTP文件夹
“ftp3.example.com/Jaz/in/”
中的四个.txt文件,但是它不会将它们复制到
“C:\Users\Jasdeep\Destination\”的目标文件夹中

注意:该列表会在瞬间显示,然后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")
您依赖服务器返回带有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")


在任何情况下,“该列表在一瞬间出现,然后Powershell关闭。”表示您没有真正调试该问题。从现有的
cmd.exe
或PowerShell控制台窗口运行脚本,以查看其完整输出,包括任何错误。

显然这不起作用:
($Allfiles-split“`r`n”)
-仅尝试
`n
使用“2”参数调用“DownloadFile”异常:“WebClient请求期间发生异常。”在C:\Users\Jas\Desktop\scripting\ftpmultipdownload.ps1:36 char:5+$webclient.DownloadFile($source,$target+$file)+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~,MethodInvocationException+FullyQualifiedErrorId:WebException 1ftp://ftp3.example.com/Jaz/In/test2.txt  test4.txt test3.txt test5.txt
非常好用!非常感谢你。你能解释一下为什么不起作用吗?请看我的最新答案。不过,一般来说,你的问题是重复的。