我以管理员身份运行cmd并输入:
- 启动powershell
当打开powershell时,我输入:
- $client = 新对象 System.Net.WebClient
- $client.DownloadFile("https://www.cse.ust.hk/msbd5003/data/fruits.txt","D:\IT\fruits.txt")
错误信息如下:
Exception calling "DownloadFile" with "2" argument(s): "The underlying connection was closed: An unexpected error occurred on a send."
At line:1 char:1
+ $client.DownloadFile("https://www.cse.ust.hk/msbd5003/data/fruits.txt ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
我尝试添加 $ client.Credentials = Get-Credential
虽然它不起作用。
最佳答案
我的猜测是,由于您是通过 https 连接,因此您可能需要设置更安全的 channel 协议(protocol)来与您尝试下载的网站进行通信。
在您的网络客户端请求之前添加此行指示安全协议(protocol)
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$client = new-object System.Net.WebClient
$client.DownloadFile("https://www.cse.ust.hk/msbd5003/data/fruits.txt","D:\IT\fruits.txt")
或者,如果您仅从一台计算机运行此脚本,则可以将 .NET 设置为默认使用安全协议(protocol)。
您可以在https://learn.microsoft.com/en-us/dotnet/framework/network-programming/tls阅读更多相关信息。
Key - HKEY_LOCAL_MACHINE\SOFTWARE\[Wow6432Node\]Microsoft\.NETFramework\<VERSION>
Name - SchUseStrongCrypto
Value - 1
此外, native PowerShell cmdlet invoke-webrequest
可以简化您的请求。
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -Uri "https://www.cse.ust.hk/msbd5003/data/fruits.txt" -OutFile "D:\IT\fruits.txt"
关于powershell - 如何修复 Windows 10 中 powershell 中的下载文件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54838248/