You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Invoke-WebRequest报403 Forbidden:手动可下载脚本无法实现求助

解决PowerShell脚本下载文件403 Forbidden错误的方案

常见原因及对应解决办法

  • 服务器验证请求来源:部分服务器会拦截非浏览器发起的请求,可添加模拟浏览器的请求头绕过验证:
    $cuser = (Get-WmiObject -Class Win32_ComputerSystem).UserName
    $source = "https://xxx/$cuser.txt"
    $destination = "C:\yyyy\$cuser.txt"
    $headers = @{
        "User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
    }
    Invoke-WebRequest -Uri $source -OutFile $destination -Headers $headers
    
  • 用户名格式不符:Get-WmiObject Win32_ComputerSystem返回的用户名格式是DOMAIN\username,若服务器文件仅用纯用户名命名,需提取用户名部分:
    $cuser = (Get-WmiObject -Class Win32_ComputerSystem).UserName.Split('\')[-1]
    $source = "https://xxx/$cuser.txt"
    $destination = "C:\yyyy\$cuser.txt"
    Invoke-WebRequest -Uri $source -OutFile $destination
    
  • 缺少会话Cookie:手动下载时浏览器会携带登录会话Cookie,脚本默认无该信息,可导出浏览器对应站点的Cookie添加到请求头:
    $cuser = (Get-WmiObject -Class Win32_ComputerSystem).UserName
    $source = "https://xxx/$cuser.txt"
    $destination = "C:\yyyy\$cuser.txt"
    $headers = @{
        "Cookie" = "替换为浏览器导出的Cookie内容"
    }
    Invoke-WebRequest -Uri $source -OutFile $destination -Headers $headers
    
  • 调整请求参数:尝试添加-UseBasicParsing参数或切换到Invoke-RestMethod:
    $cuser = (Get-WmiObject -Class Win32_ComputerSystem).UserName
    $source = "https://xxx/$cuser.txt"
    $destination = "C:\yyyy\$cuser.txt"
    Invoke-RestMethod -Uri $source -OutFile $destination -UseBasicParsing
    

内容的提问来源于stack exchange,提问作者Marco Gentilesca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 12:02:44