Powershell-为什么使用 Invoke-WebRequest 比下载浏览器慢得多?

我使用 Powershell 的 Invoke-WebRequest方法从 AmazonS3下载一个文件到我的 WindowsEC2实例。

如果我使用 Chrome 下载文件,我可以在5秒内下载200MB 的文件。在 PowerShell 中使用 Invoke-WebRequest下载同样的文件最多需要5分钟。

为什么使用 Invoke-WebRequest比较慢,有没有办法在 PowerShell 脚本中全速下载?

49015 次浏览

I was using

Invoke-WebRequest $video_url -OutFile $local_video_url

I changed the above to

$wc = New-Object net.webclient
$wc.Downloadfile($video_url, $local_video_url)

This restored the download speed to what I was seeing in my browsers.

I just hit this issue today, if you change the ContentType argument to application/octet-stream it is much faster (as fast as using webclient). The reason is because the Invoke-Request command will not try and parse the response as JSON or XML.

Invoke-RestMethod -ContentType "application/octet-stream" -Uri $video_url  -OutFile $local_video_url

Without switching away from Invoke-WebRequest, turning off the progress bar did it for me. I found the answer from this thread: https://github.com/PowerShell/PowerShell/issues/2138 (jasongin commented on Oct 3, 2016)

$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest <params>

For my 5MB file on localhost, the download time went from 30s to 250ms.

Note that to get the progress bar back in the active shell, you need to call $ProgressPreference = 'Continue'.

One-liner to download a file to the temp directory:

(New-Object Net.WebClient).DownloadFile("https://www.google.com", "$env:temp\index.html")

$ProgressPreference = 'SilentlyContinue' I got this down from 52min down to 14sec, for a file of 450 M. Spectacular.