[英]powershell System.Net.WebClient.DownloadFile(String, String) throws cryptic errors
[英]File appears corrupted when it's downloaded with System.Net.WebClient.DownloadFile
我將一個文件上傳到雲,它給了我直接下載鏈接。
通過單擊此鏈接下載它可以正常工作,但是當我嘗試通過 Powershell 上的System.Net.WebClient.DownloadFile下載它時,它會下載文件,但是當我打開它時,它說文件已損壞且無法讀取。
那是代碼:
$WebClient = New-Object System.Net.WebClient
$WebClient.DownloadFile("https://xxxxxx.com/xxxxx/xxx.exe","C:\Users\user\Desktop\xxx.exe")
有什么解決辦法嗎?
奇怪,這個邏輯對我有用。
您可以嘗試添加$WebClient.Dispose()
嗎?
或其他PowerShell下載方法如:
$uri = "https://xxxxxx.com/xxxxx/xxx.exe"
$path = "C:\Users\user\Desktop\xxx.exe"
Invoke-WebRequest -Uri $uri -OutFile $path
<#
# 1. Invoke-WebRequest
The first and most obvious option is the Invoke-WebRequest cmdlet. It is built
into PowerShell and can be used in the following method:
#>
$url = "http://mirror.internode.on.net/pub/test/10meg.test"
$output = "$PSScriptRoot\10meg.test"
$start_time = Get-Date
Invoke-WebRequest -Uri $url -OutFile $output
Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"
<#
2. System.Net.WebClient
A common .NET class used for downloading files is the System.Net.WebClient class.
#>
$url = "http://mirror.internode.on.net/pub/test/10meg.test"
$output = "$PSScriptRoot\10meg.test"
$start_time = Get-Date
$wc = New-Object System.Net.WebClient
$wc.DownloadFile($url, $output)
# OR
(New-Object System.Net.WebClient).DownloadFile($url, $output)
Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"
<#
3. Start-BitsTransfer
If you haven't heard of BITS before, check this out. BITS is primarily designed
for asynchronous file downloads, but works perfectly fine synchronously too
(assuming you have BITS enabled).
#>
$url = "http://mirror.internode.on.net/pub/test/10meg.test"
$output = "$PSScriptRoot\10meg.test"
$start_time = Get-Date
Import-Module BitsTransfer
Start-BitsTransfer -Source $url -Destination $output
# Or
Start-BitsTransfer -Source $url -Destination $output -Asynchronous
Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"
這是我個人每天使用的,來自通過我的個人資料導入的個人模塊中的 function。
$webclient = New-Object System.Net.WebClient
$url = 'https://download.microsoft.com/download/B/A/4/BA4A7E71-2906-4B2D-A0E1-80CF16844F5F/dotNetFx45_Full_setup.exe'
$filename = [System.IO.Path]::GetFileName($url)
$file = "$TechToolsUNC\$filename"
$webclient.DownloadFile($url,$file)
Start-Process $file -Wait
我推測他與 powershell 無關,而是您的機器或網絡上的其他因素,很可能是防病毒代理等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.