PowerShell 7.3.7中Invoke-WebRequest不支持FTP的解决方法及替代方案
PowerShell 7.3.7下载FTP文件的解决方法
PowerShell 7.x的Invoke-WebRequest确实不再支持FTP协议,给你几个可行的替代方案:
方法1:使用.NET的WebClient类
这是最直接的方式,匿名FTP直接用下面的代码:
$webClient = New-Object System.Net.WebClient $webClient.DownloadFile("ftp://ftp.sanger.ac.uk/pub/users/kp9/demo-vdj.h5ddl", "demo-vdj.h5ddl")
如果需要验证账号密码,加上凭证即可:
$credentials = New-Object System.Net.NetworkCredential("你的FTP用户名", "你的FTP密码") $webClient = New-Object System.Net.WebClient $webClient.Credentials = $credentials $webClient.DownloadFile("ftp://ftp.sanger.ac.uk/pub/users/kp9/demo-vdj.h5ddl", "demo-vdj.h5ddl")
方法2:使用系统原生curl命令
Windows 10及以上版本默认自带curl,Linux/macOS也原生支持,直接用curl下载:
curl ftp://ftp.sanger.ac.uk/pub/users/kp9/demo-vdj.h5ddl -o demo-vdj.h5ddl
需要账号密码的话,把凭证放在URL里:
curl ftp://用户名:密码@ftp.sanger.ac.uk/pub/users/kp9/demo-vdj.h5ddl -o demo-vdj.h5ddl
方法3:使用.NET的FtpWebRequest(更底层)
如果需要更精细的控制,比如进度监控,可以用FtpWebRequest:
# 创建FTP请求 $ftpUrl = "ftp://ftp.sanger.ac.uk/pub/users/kp9/demo-vdj.h5ddl" $ftpRequest = [System.Net.FtpWebRequest]::Create($ftpUrl) $ftpRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile # 匿名登录用空凭证,需要账号密码就替换成实际信息 $ftpRequest.Credentials = New-Object System.Net.NetworkCredential("anonymous", "") # 执行下载 $response = $ftpRequest.GetResponse() $responseStream = $response.GetResponseStream() $fileStream = [System.IO.File]::Create("demo-vdj.h5ddl") $responseStream.CopyTo($fileStream) # 清理资源 $fileStream.Close() $responseStream.Close() $response.Close()
内容的提问来源于stack exchange,提问作者mightyandweakcoder
相关产品推荐
相关产品推荐

