在windows下使用powershell自帶命令下載文件時有以下4種方式:
- Invoke-WebRequest
- Invoke-RestMethod
- Start-BitsTransfer
- System.Net.WebClient
前提,需要powershell 5.1(win10默認就是)
實驗,在同一台機器(5G 400Mbps)上下載同一個文件(123MB),查看異同
一、Invoke-WebRequest
可以下載http,https,ftp資源
使用: Invoke-WebRequest -Uri <source> -OutFile <destination>
可以看出,在下載過程中,程序是先讀取至內存中的,全部讀取完后再寫入文件,在讀取過程中,文件大小為0
我們再看看下載時長:
1分15秒
二、Invoke-RestMethod
和RestWebRequest類似,區別在於RestMethod支持json和XML內容的代碼,會嘗試適當的解碼器來讀取,不支持HTML
使用: Invoke-RestMethod -Uri <source> -OutFile <destination>
再看看時長:
1分31秒
三、Start-BitTransfer
這是windows自帶的一個程序, 支持斷點續傳、下不同文件等,有需要的可以查看后面的參考鏈接
使用: Start-BitsTransfer -Source $source -Destination $destination
下載過程
與上面不同的是,下載前會先占用磁盤大小,生成tmp文件
時間:
1分35秒
四、System.Net.WebClient
使用:(new-object System.Net.WebClient).DownloadFile('src_url', 'dst_file'))
時長
綜上:4種方式下載文件在時間 長差距不大,所以根據所需選用
參考文檔:
https://adamtheautomator.com/powershell-download-file/