You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows7下PowerShell5.0多FTP文件下载脚本问题求助

解决PowerShell 5.0 FTP通配符批量下载失效的问题

嘿,我懂你遇到的糟心事——单个文件下载顺顺当当,一用通配符批量下载就直接歇菜对吧?这其实是因为PowerShell 5.0里的原生FTP工具(不管是WebClient还是传统ftp命令)都不支持直接识别FTP服务器上的通配符。要搞定批量下载,得先手动拉取服务器上的文件列表,筛选出符合你通配符规则的文件,再逐个下载。

下面是我整理好的完整解决脚本,你可以直接套用修改:

# FTP服务器配置信息
$ftpServer = "ftp://你的FTP服务器地址/"
$remotePath = "服务器上的目标文件夹路径/" # 比如:docs/reports/
$localPath = "本地保存文件的路径/" # 比如:D:\Downloads\FTPFiles\
$username = "你的FTP用户名"
$password = "你的FTP密码"
$wildcardPattern = "*.txt" # 你要匹配的通配符,比如*.zip、data_*.csv

# 创建FTP请求获取服务器文件列表
$ftpRequest = [System.Net.FtpWebRequest]::Create($ftpServer + $remotePath)
$ftpRequest.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectory
$ftpRequest.Credentials = New-Object System.Net.NetworkCredential($username, $password)

try {
    # 获取并解析文件列表
    $ftpResponse = $ftpRequest.GetResponse()
    $responseStream = $ftpResponse.GetResponseStream()
    $streamReader = New-Object System.IO.StreamReader($responseStream)
    # 筛选出符合通配符规则的非空文件名
    $fileList = $streamReader.ReadToEnd().Split("`n") | Where-Object { $_ -match $wildcardPattern -and $_ -ne "" }
    
    # 确保本地保存路径存在,不存在就创建
    if (-not (Test-Path $localPath)) {
        New-Item -ItemType Directory -Path $localPath | Out-Null
    }

    # 逐个下载符合条件的文件
    foreach ($file in $fileList) {
        $remoteFileUrl = $ftpServer + $remotePath + $file
        $localFileFullPath = Join-Path $localPath $file
        
        $downloadRequest = [System.Net.FtpWebRequest]::Create($remoteFileUrl)
        $downloadRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
        $downloadRequest.Credentials = New-Object System.Net.NetworkCredential($username, $password)
        
        $downloadResponse = $downloadRequest.GetResponse()
        $downloadStream = $downloadResponse.GetResponseStream()
        $fileStream = New-Object System.IO.FileStream($localFileFullPath, [System.IO.FileMode]::Create)
        
        $downloadStream.CopyTo($fileStream)
        
        # 关闭流和响应,释放资源
        $fileStream.Close()
        $downloadStream.Close()
        $downloadResponse.Close()
        
        Write-Host "成功下载文件: $file"
    }

    # 关闭初始请求的相关流和响应
    $streamReader.Close()
    $responseStream.Close()
    $ftpResponse.Close()
}
catch {
    Write-Host "下载过程出错: $_"
}

关键细节说明:

  • 我用FtpWebRequest主动获取服务器文件列表,而不是直接在URL里加通配符——因为绝大多数FTP服务器不支持通过URL通配符返回匹配文件。
  • 用Where-Object结合你设置的$wildcardPattern筛选文件,确保只下载你需要的类型。
  • 每个文件单独创建下载请求,和你之前单个文件下载的逻辑一致,避免批量操作的兼容性问题。

如果你的FTP服务器允许匿名登录,只需要把$username和$password留空,脚本会自动用匿名身份连接。

内容的提问来源于stack exchange,提问作者Rob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:44:34