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

如何用Invoke-WebRequest下载Opera 64位安装包并处理文件名与路径?

解决Opera安装包PowerShell下载问题

问题原因

你遇到的问题源于Opera提供的下载链接是重定向跳转链接,并非直接指向安装包文件。浏览器会自动处理重定向并解析响应头中的文件名,但Invoke-WebRequest默认配置无法直接完成这些操作,导致无法正确下载文件。


解决方案(同时满足三个需求)

以下是分步实现和完整脚本:

1. 模拟浏览器点击式下载

通过配置Invoke-WebRequest跟随重定向,让PowerShell像浏览器一样处理跳转:

$operaRedirectUrl = "https://download.opera.com/download/get/?partner=www&opsys=Windows&arch=x64"
# 允许最多5次重定向,覆盖常见跳转场景
$response = Invoke-WebRequest -Uri $operaRedirectUrl -MaximumRedirection 5

2. 获取带版本号的真实文件名

服务器会在响应头的Content-Disposition字段中返回包含版本信息的文件名,通过正则提取:

$contentDisposition = $response.Headers['Content-Disposition']
# 匹配filename字段内容
$fileName = [regex]::Match($contentDisposition, 'filename=(.+)').Groups[1].Value
# 移除可能存在的引号
$fileName = $fileName -replace '"', ''

3. 指定自定义路径保存

自行设置保存路径,确保路径存在后再保存文件:

# 替换为你的目标路径
$savePath = "D:\MyDownloads"

# 路径不存在则自动创建
if (-not (Test-Path -Path $savePath)) {
    New-Item -Path $savePath -ItemType Directory | Out-Null
}

# 拼接完整保存路径
$fullSavePath = Join-Path -Path $savePath -ChildPath $fileName

# 以字节编码保存文件,避免损坏
$response.Content | Set-Content -Path $fullSavePath -Encoding Byte

完整可运行脚本

$operaRedirectUrl = "https://download.opera.com/download/get/?partner=www&opsys=Windows&arch=x64"
$savePath = "D:\MyDownloads"  # 修改为你的自定义路径

try {
    # 获取响应并处理重定向
    $response = Invoke-WebRequest -Uri $operaRedirectUrl -MaximumRedirection 5 -ErrorAction Stop
    
    # 解析真实文件名
    $contentDisposition = $response.Headers['Content-Disposition']
    $fileName = [regex]::Match($contentDisposition, 'filename=(.+)').Groups[1].Value
    $fileName = $fileName -replace '"', ''
    
    # 确保保存路径存在
    if (-not (Test-Path -Path $savePath)) {
        New-Item -Path $savePath -ItemType Directory | Out-Null
    }
    
    # 保存文件到指定路径
    $fullSavePath = Join-Path -Path $savePath -ChildPath $fileName
    $response.Content | Set-Content -Path $fullSavePath -Encoding Byte
    
    Write-Host "下载成功!文件路径:$fullSavePath"
}
catch {
    Write-Host "下载失败:$($_.Exception.Message)"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:45:50