首页 > 解决方案 > 在 powershell 2 中使用 DownloadFile 下载文件时出错

问题描述

我需要在powershell 2下下载文件。

由于版本 2 不支持 Invoke-WebRequest,我尝试使用 DownloadFile 但我总是遇到相同的错误,我不知道如何修复它。

 PS C:\Users\user> [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

:: : Exception setting "SecurityProtocol": "Cannot convert null to type "System.Net.SecurityProtocolType" due to invali
d enumeration values. Specify one of the following enumeration values and try again. The possible enumeration values ar
e "Ssl3, Tls"."
At line:1 char:28
+ [Net.ServicePointManager]:: <<<< SecurityProtocol = [Net.SecurityProtocolType]::Tls12
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyAssignmentException

PS C:\Users\user> $client = new-object System.Net.WebClient

PS C:\Users\user> $client.DownloadFile("https://web.com/test.txt", "C:\Users\user\Desktop\test.txt")
DownloadFile : Exception calling "DownloadFile" with "2" argument(s): "The underlying connection was closed: An unexpec
ted error occurred on a send."
At line:1 char:21
+ $client.DownloadFile <<<< ("https://web.com/test.txt", "C:\Users\user\Desktop\test.txt")
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

我可以做什么?

标签: powershellpowershell-2.0

解决方案


如果您在设置 TLS 版本时遇到错误,您可能需要检查哪些协议可用:

[Net.SecurityProtocolType]::GetValues( 'Net.SecurityProtocolType' )

但是,我不知道使用这么旧的版本会如何影响协议的可用性。此外,我不知道给定系统上的特定协议设置如何影响整个协议的可用性或上述命令返回的协议的可用性。

事实上,我会指出错误本身只反映 SSL3 和 Tls。在我的系统上,当我输入无效的枚举器时,错误报告Ssl3,Tls,Tls11,Tls12,Tls13为选项。虽然我的系统配置为禁用 Tls12 以下的所有内容并且没有为 Tls13 定义任何设置。

我可以做出的最好假设是与 PowerShell 2.0 一起使用的 .Net 2.0 不能使用 Tls12,因为它不存在于枚举器中,并且根据与我的系统的比较,枚举不受协议的显式启用/禁用的影响。

无论如何,我认为您必须先清除第一个错误,然后再担心第二个错误。第二个错误很可能是由于 TLS 不兼容造成的。最简单的方法是升级 PowerShell(连同所需的 .Net 版本)。PowerShell 2.0 可以与 Windows PowerShell 5.1 共存,但您可能必须使用-Version 2.0参数启动。此外,请确保引擎已作为 Windows 功能安装。免责声明:请自行验证所有内容。

我知道 Windows PowerShell 2.0 引擎 (PowerShell-V2) 至少在 Windows 2012 R2 之后才作为一项功能提供。

我还要指出,PowerShell 7.x(又名 PowerShell Core)可以与 Windows PowerShell 一起安装。这可能会回避上述复杂性,让您可以执行手头的任务......


推荐阅读