使用PowerShell下载指定CSV文件链接,代码异常求排查
你的PowerShell下载代码存在的问题及修正方案
代码核心问题
- 参数类型不匹配:
Invoke-WebRequest执行后返回的是Microsoft.PowerShell.Commands.HtmlWebResponseObject类型的响应对象,但WebClient.DownloadFile()的第一个参数要求是字符串格式的URL(或Uri对象),直接传入响应对象会触发类型错误。 - 冗余请求操作:先调用
Invoke-WebRequest发起一次请求,接着又用WebClient发起第二次请求,完全没必要,重复请求既浪费资源,还可能触发目标网站的反爬限制。 - 缺少路径合法性检查:如果目标路径
C:\filelocation\不存在,下载操作会直接抛出错误,没有提前创建目录的逻辑。 - 使用过时API:
System.Net.WebClient是.NET Framework中的旧API,在PowerShell 5.1及以上版本,更推荐使用Invoke-WebRequest这类原生cmdlet,语法更贴合PowerShell生态,维护性更强。
修正方案1:使用原生PowerShell cmdlet(推荐)
$url = 'https://nfs.faireconomy.media/ff_calendar_thisweek.csv?version=59fa0f4b59dfe70e557208f86ab2d2a0' $destination = "C:\filelocation\thisweek.csv" # 检查目标目录是否存在,不存在则创建 $destDir = Split-Path -Path $destination -Parent if (-not (Test-Path -Path $destDir)) { New-Item -ItemType Directory -Path $destDir | Out-Null } # 直接下载到指定文件 Invoke-WebRequest -Uri $url -OutFile $destination -UseBasicParsing
修正方案2:修复原WebClient写法
$url = 'https://nfs.faireconomy.media/ff_calendar_thisweek.csv?version=59fa0f4b59dfe70e557208f86ab2d2a0' $destination = "C:\filelocation\thisweek.csv" # 检查并创建目标目录 $destDir = Split-Path -Path $destination -Parent if (-not (Test-Path -Path $destDir)) { New-Item -ItemType Directory -Path $destDir | Out-Null } $webClient = New-Object System.Net.WebClient $webClient.DownloadFile($url, $destination) $webClient.Dispose() # 手动释放资源
内容的提问来源于stack exchange,提问作者iceman
相关产品推荐
相关产品推荐

