文件在使用 System.Net.WebClient.DownloadFile 下载时似乎已损坏



我上传了一个文件到云中,这给了我直接下载链接。

通过单击此链接下载它工作正常,但是当我尝试通过Powershell上的System.Net.WebClient.DownloadFile下载它时,它会下载文件,但是当我打开它时,它说该文件已损坏且无法读取

这就是代码:

$WebClient = New-Object System.Net.WebClient
$WebClient.DownloadFile("https://xxxxxx.com/xxxxx/xxx.exe","C:UsersuserDesktopxxx.exe")

有什么解决办法吗?

奇怪,这个逻辑对我有用。

您可以尝试添加$WebClient.Dispose()

或其他 PowerShell 下载方法,例如:

$uri = "https://xxxxxx.com/xxxxx/xxx.exe"
$path = "C:UsersuserDesktopxxx.exe"
Invoke-WebRequest -Uri $uri -OutFile $path

使用 PowerShell 下载文件的 3 种方法

<#
# 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 = "$PSScriptRoot10meg.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 = "$PSScriptRoot10meg.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 = "$PSScriptRoot10meg.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)"

这是我个人每天使用的功能,来自通过我的个人资料导入的个人模块中的功能。

$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,而是你的机器或网络上的其他因素,很可能是防病毒代理等。

最新更新