提问人:Lloyd Banks 提问时间:2/24/2015 更新时间:9/7/2023 访问量:63810
Powershell - 为什么使用 Invoke-WebRequest 比浏览器下载慢得多?
Powershell - Why is Using Invoke-WebRequest Much Slower Than a Browser Download?
问:
我使用 Powershell 的方法将文件从 Amazon S3 下载到我的 Windows EC2 实例。Invoke-WebRequest
如果我使用 Chrome 下载文件,我能够在 5 秒内下载一个 200 MB 的文件。在 PowerShell 中使用相同的下载最多需要 5 分钟。Invoke-WebRequest
为什么使用速度较慢,有没有办法在 PowerShell 脚本中全速下载?Invoke-WebRequest
答:
我正在使用
Invoke-WebRequest $video_url -OutFile $local_video_url
我把上面改成了
$wc = New-Object net.webclient
$wc.Downloadfile($video_url, $local_video_url)
这将下载速度恢复到我在浏览器中看到的速度。
评论
wc.downloadFile(ibm-s3-url, "./test.tar.gz")
我今天刚刚遇到了这个问题,如果您将 ContentType 参数更改为 application/octet-stream,它会快得多(与使用 webclient 一样快)。原因是 Invoke-Request 命令不会尝试将响应解析为 JSON 或 XML。
Invoke-RestMethod -ContentType "application/octet-stream" -Uri $video_url -OutFile $local_video_url
评论
-ContentType
仅适用于 AFAIK 请求,因此可能不会产生任何影响。POST
-UseBasicParsing
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest
在不切换的情况下,关闭进度条为我做到了。我从这个线程中找到了答案:https://github.com/PowerShell/PowerShell/issues/2138(jasongin于2016年10月3日发表评论)Invoke-WebRequest
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest <params>
对于我在 localhost 上的 5MB 文件,下载时间从 30 秒到 250 毫秒。
请注意,要在活动 shell 中恢复进度条,您需要调用 .$ProgressPreference = 'Continue'
评论
-ProgressPreference
Invoke-WebRequest
将文件下载到临时目录的单行代码:
(New-Object Net.WebClient).DownloadFile("https://www.google.com", "$env:temp\index.html")
评论
Invoke-WebRequest
,OP 已经在使用,在内部执行相同的操作。WebClient.DownloadFile
$ProgressPreference = 'SilentlyContinue'
我把它从 52 分钟缩短到 14 秒,对于一个 450 M 的文件。
壮观。
评论
Invoke-WebRequest
Invoke-WebRequest
Invoke-RestMethod
不幸的是,Windows Powershell 5.1(Windows 操作系统中包含的版本)上的进度条大大减慢了文件下载速度。在以后的 Powershell 版本上要快得多(我在 Powershell 7.3 上测试了它)。Invoke-WebRequest
IMO,如果您被迫使用 Windows Powershell,那么最好的方法是使用 curl,因为它现在默认包含在 Windows 上。请注意,默认情况下,Windows Powershell 具有别名,因此要运行程序,您需要写信告诉 Windows Powershell 您不想使用别名。curl
Invoke-WebRequest
curl
curl.exe
curl
此命令在 Windows Powershell 5.1 上需要 11 分钟,在 Powershell 7.3 上需要 23 秒:
Invoke-WebRequest -Verbose -Uri "https://download.visualstudio.microsoft.com/download/pr/7c048383-52b1-47cb-91d1-acfaf1a3fcc9/ea510c0bfa44f33cc3ddea79090a51e1/dotnet-sdk-6.0.410-win-x64.exe" -OutFile ".\dotnet-sdk-6.0.410-win-x64.exe"
这需要 15 秒:
curl.exe -fSLo .\dotnet-sdk-6.0.410-win-x64.exe https://download.visualstudio.microsoft.com/download/pr/7c048383-52b1-47cb-91d1-acfaf1a3fcc9/ea510c0bfa44f33cc3ddea79090a51e1/dotnet-sdk-6.0.410-win-x64.exe
评论