1. 为什么选择PowerShell下载游戏?
作为一名常年帮朋友解决各种电脑问题的"技术支援",我遇到过无数次"帮我下个游戏"的请求。原神作为当下热门的开放世界游戏,客户端体积高达数十GB,用传统浏览器下载经常遇到断线重连、速度不稳定等问题。而PowerShell作为Windows系统内置的强大工具,完全可以成为游戏下载的利器。
我最初发现PowerShell下载大文件的优势是在帮同事搬运虚拟机镜像时。相比浏览器单线程下载,PowerShell的Invoke-WebRequest命令支持断点续传,配合-OutFile参数可以直接保存到指定路径,还能通过-BytesPerSecond参数限速(避免影响他人上网)。最重要的是,它不需要安装任何第三方软件,这对很多公司限制安装权限的环境特别友好。
2. 准备工作与环境检查
2.1 确认PowerShell版本
首先按Win+R输入powershell打开控制台,执行:
powershell复制$PSVersionTable.PSVersion
理想情况应显示5.1或更高版本。如果版本低于4.0(Win7默认是2.0),需要先升级:
powershell复制# 对于Win7用户
iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
choco install powershell -y
注意:公司域控环境可能需要管理员权限,家用电脑直接运行即可。
2.2 获取原神下载链接
官方启动器下载页面通常需要人工点击,但我们可以直接从CDN获取直链。通过浏览器开发者工具(F12)分析网络请求,可以发现类似这样的下载地址:
code复制https://autopatchcn.yuanshen.com/client/download/launcher/20210621094322_fp3L3c/GenshinImpact_install_20210621094322.exe
建议先用浏览器测试链接有效性,因为CDN地址会随时间变化。也可以从米哈游API获取最新地址:
powershell复制$api = Invoke-RestMethod -Uri "https://sdk-static.mihoyo.com/hk4e_cn/mdk/launcher/api/resource?launcher_id=10&key=gcStgarh"
$api.data.game.latest.decompressed_path
3. 核心下载脚本实现
3.1 基础下载命令
最简单的单线程下载:
powershell复制Invoke-WebRequest -Uri "下载链接" -OutFile "D:\GenshinImpact_install.exe"
但这样无法显示进度条,改进版本:
powershell复制$ProgressPreference = 'Continue'
$client = New-Object System.Net.WebClient
$client.DownloadFile("下载链接", "D:\GenshinImpact_install.exe")
3.2 多线程加速方案
通过分割文件实现多线程下载(需要PowerShell 7+):
powershell复制$uri = "下载链接"
$outPath = "D:\GenshinImpact_install.exe"
$threads = 4
$totalSize = (Invoke-WebRequest -Uri $uri -Method Head).Headers.'Content-Length'
$chunkSize = [math]::Ceiling($totalSize / $threads)
$jobs = 1..$threads | ForEach-Object {
$start = ($_ - 1) * $chunkSize
$end = $start + $chunkSize - 1
if($_ -eq $threads) { $end = $totalSize - 1 }
Start-ThreadJob -ScriptBlock {
$headers = @{ Range = "bytes=$($using:start)-$($using:end)" }
Invoke-WebRequest -Uri $using:uri -Headers $headers -OutFile "$($using:outPath).part$_"
}
}
$jobs | Wait-Job
Get-Content -Path "$outPath.part*" -Encoding Byte -Raw | Set-Content -Path $outPath -Encoding Byte -NoNewline
Remove-Item "$outPath.part*"
3.3 断点续传实现
通过检查本地文件大小实现断点续传:
powershell复制$uri = "下载链接"
$outPath = "D:\GenshinImpact_install.exe"
if(Test-Path $outPath) {
$localSize = (Get-Item $outPath).Length
$headers = @{ Range = "bytes=$localSize-" }
} else {
$headers = @{}
}
$request = [System.Net.HttpWebRequest]::Create($uri)
$request.AddRange($localSize)
$response = $request.GetResponse()
$stream = $response.GetResponseStream()
$fileStream = [System.IO.File]::OpenWrite($outPath)
$fileStream.Seek($localSize, [System.IO.SeekOrigin]::Begin) | Out-Null
$buffer = New-Object byte[] 1MB
while(($read = $stream.Read($buffer, 0, $buffer.Length)) -gt 0) {
$fileStream.Write($buffer, 0, $read)
Write-Progress -Activity "下载中" -Status "$([math]::Round($fileStream.Position/1MB))MB/$([math]::Round($response.ContentLength/1MB))MB" -PercentComplete ($fileStream.Position/$response.ContentLength*100)
}
$fileStream.Close()
$stream.Close()
4. 实用技巧与异常处理
4.1 绕过公司网络限制
有些企业网络会拦截大文件下载,可以尝试:
powershell复制# 使用HTTPS并忽略证书错误
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
$WebClient = New-Object System.Net.WebClient
$WebClient.DownloadFile("https://下载链接", "D:\GenshinImpact_install.exe")
# 或通过代理(需替换实际代理地址)
$proxy = New-Object System.Net.WebProxy("http://proxy.example.com:8080", $true)
$WebClient.Proxy = $proxy
4.2 下载速度优化
通过调整TCP参数提升下载速度(需要管理员权限):
powershell复制# 修改TCP窗口大小
Set-NetTCPSetting -SettingName InternetCustom -InitialCongestionWindow 10 -CongestionProvider CTCP
# 关闭自动调谐
netsh interface tcp set global autotuninglevel=restricted
4.3 常见错误处理
问题1:内存不足
powershell复制# 改用流式处理
$request = [System.Net.HttpWebRequest]::Create($uri)
$response = $request.GetResponse()
$stream = $response.GetResponseStream()
$fileStream = [System.IO.File]::Create($outPath)
$stream.CopyTo($fileStream)
$fileStream.Close()
问题2:SSL/TLS错误
powershell复制# 强制使用TLS1.2
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
问题3:中文路径问题
powershell复制# 使用ASCII编码处理路径
$outPath = [System.Text.Encoding]::ASCII.GetString([System.Text.Encoding]::Unicode.GetBytes("D:\原神安装包.exe"))
5. 自动化安装与更新
5.1 静默安装参数
获取到安装包后,可以通过以下命令自动安装:
powershell复制Start-Process -FilePath "GenshinImpact_install.exe" -ArgumentList "/S /D=C:\Games\Genshin Impact" -Wait
5.2 定期检查更新
创建计划任务每周检查更新:
powershell复制$action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File D:\check_update.ps1"
$trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Sunday -At 3am
Register-ScheduledTask -TaskName "GenshinUpdateCheck" -Action $action -Trigger $trigger
检查脚本示例:
powershell复制$localVer = (Get-Item "C:\Games\Genshin Impact\GenshinImpact.exe").VersionInfo.FileVersion
$onlineVer = (Invoke-RestMethod "https://sdk-static.mihoyo.com/hk4e_cn/mdk/launcher/api/resource?launcher_id=10").data.game.latest.version
if($localVer -ne $onlineVer) {
# 触发下载逻辑
& "D:\download_script.ps1"
# 发送通知
[System.Windows.Forms.MessageBox]::Show("原神有新版本可用!","更新提示")
}
6. 安全注意事项
- 下载源验证:务必从官方CDN下载,避免第三方修改的安装包包含恶意软件。可以通过验证文件哈希确认完整性:
powershell复制$officialHash = "a1b2c3d4e5..." # 从官网获取
$localHash = (Get-FileHash -Path "GenshinImpact_install.exe" -Algorithm SHA256).Hash
if($localHash -ne $officialHash) { Remove-Item -Path "GenshinImpact_install.exe" -Force }
- 网络流量监控:企业环境中大量下载可能触发流量警报,建议:
- 使用
-BytesPerSecond参数限速 - 避开工作时间段下载
- 分多个小文件下载后合并
- 权限最小化:不要使用管理员身份运行下载脚本,避免恶意代码利用高权限:
powershell复制# 检查当前权限
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Warning "建议使用普通用户权限运行下载脚本"
Exit 1
}
