如何解决PowerShell使用WebClient下载文件时触发WebException报错问题
问题修复方案
核心错误点
System.Net.WebClient的DownloadFile方法要求第二个入参为完整的目标文件绝对路径,你当前传入的是文件夹路径,程序无法直接将文件内容写入文件夹对象,因此触发报错。
修复后可直接运行的代码
# 同时兼容TLS1.2和TLS1.3,适配当前多数站点的安全协议要求 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12, [Net.SecurityProtocolType]::Tls13 $url = "https://nodejs.org/dist/v14.17.6/node-v14.17.6-x64.msi" $folder = "C:\Users\test\Downloads" # 拼接得到完整的文件保存路径 $savePath = Join-Path -Path $folder -ChildPath "node-v14.17.6-x64.msi" $WebClient = New-Object System.Net.WebClient $WebClient.DownloadFile($url, $savePath)
其他场景排查项
如果修改后仍报错,可依次检查以下项:
- 校验路径权限:确认当前PowerShell运行身份对目标保存目录有写入权限,可手动在该目录下新建文件验证
- 校验网络连通性:运行
Test-NetConnection nodejs.org -Port 443确认可正常访问目标站点,排除代理、防火墙、企业内网拦截问题 - 校验路径合法性:确认保存路径中无违规特殊字符,涉及空格的路径确保用引号包裹,对应磁盘分区已正常挂载
替代实现方案
也可以直接使用PowerShell原生的Invoke-WebRequest命令实现相同下载逻辑,代码如下:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12, [Net.SecurityProtocolType]::Tls13 $url = "https://nodejs.org/dist/v14.17.6/node-v14.17.6-x64.msi" $savePath = "C:\Users\test\Downloads\node-v14.17.6-x64.msi" Invoke-WebRequest -Uri $url -OutFile $savePath -UseBasicParsing
内容的提问来源于stack exchange,提问作者user310291
相关产品推荐
相关产品推荐

