如何使用PowerShell从SourceForge下载文件以实现KeePass自动更新
方案1:直接调用latest下载链接(快速可用)
调整参数后的可用代码如下:
$downloadUrl = "https://sourceforge.net/projects/keepass/files/latest/download" $outputPath = "$env:USERPROFILE\Downloads\KeePass2-Latest.exe" Invoke-WebRequest -Uri $downloadUrl ` -OutFile $outputPath ` -UseBasicParsing ` -MaximumRedirection 10 ` -UserAgent "Wget/1.21.1"
参数说明:
-UseBasicParsing:跳过依赖IE内核的DOM解析逻辑,适配无GUI的命令行运行场景,避免兼容性问题-MaximumRedirection 10:SourceForge下载链路通常有3~5次跳转,调高重定向次数上限可完整走完跳转流程-UserAgent "Wget/1.21.1":使用标准命令行下载工具的UA标识,匹配SourceForge直接返回文件的规则,比设置空UA更稳定
方案2:预解析版本号下载(更适合批量更新场景)
如果需要做版本校验、避免重复下载相同版本,可以先抓取最新版本号再拼接下载链接,稳定性更高:
# 抓取最新正式版本号 $releasePageContent = Invoke-WebRequest -Uri "https://keepass.info/download.html" -UseBasicParsing $latestVersion = ($releasePageContent.Links | Where-Object { $_.href -match 'KeePass-([\d.]+)-Setup.exe' } | Select-Object -First 1).href -replace '.*KeePass-([\d.]+)-Setup.exe', '$1' # 拼接固定格式的SourceForge下载链接 $downloadUrl = "https://sourceforge.net/projects/keepass/files/KeePass%202.x/$latestVersion/KeePass-$latestVersion-Setup.exe/download" $outputPath = "$env:USERPROFILE\Downloads\KeePass2-$latestVersion-Setup.exe" # 执行下载 Invoke-WebRequest -Uri $downloadUrl ` -OutFile $outputPath ` -UseBasicParsing ` -MaximumRedirection 10 ` -UserAgent "Wget/1.21.1"
内容的提问来源于stack exchange,提问作者rovda
相关产品推荐
相关产品推荐

