powershell - 如何修复 Windows 10 中 powershell 中的下载文件错误

标签 powershell windows-10

我以管理员身份运行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/

相关文章:

linux - 如何将此 powershell 脚本转换为 bin/sh 脚本?

powershell - 为什么需要定义$ id = 1?

powershell - Get-ChildItem 的作用类似于 ls 而不是 ls -l

windows - 如何在 PowerShell 中比较两个文件夹并创建缺失的子文件夹

c# - Windows 10 家庭版/专业版/企业版 IIS 的并发请求限制

c# - UWP Windows 10 应用程序内存在导航时增加

windows-10 - 如何让 Vagrant Homestead 使用 Hyper-V 启动

powershell - Powershell V5.0 中缺少帮助文件

windows - Azure AD : 50155 Device authentication failed

windows-10 - 为什么 make.exe 尝试在 Windows 上运行/usr/bin/sh?