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

通过Intune部署7zip更新修复脚本时出现路径不存在等PowerShell错误

解决Intune部署7zip更新检测脚本的错误

错误原因分析

  1. WindowsApps路径访问权限问题:Intune脚本默认以SYSTEM账户运行,该账户没有访问C:\Program Files (x86)\WindowsApps的权限(此文件夹属于当前用户的受保护目录),而本地运行时使用的是当前登录用户,因此能正常访问。
  2. Winget路径获取失败导致执行错误:由于$Winget变量未获取到有效路径,执行&$winget upgrade时会因变量为空抛出“无效对象”错误。

修复方案

修改后的检测脚本

$app_2upgrade = "7zip.7zip"

# 优先通过系统PATH定位winget.exe
try {
    $wingetPath = (Get-Command winget.exe -ErrorAction Stop).Source
}
catch {
    # PATH中找不到时,从SYSTEM账户可访问的WindowsApps路径查找
    $wingetPath = Get-ChildItem -Path "C:\Program Files\WindowsApps\Microsoft.DesktopAppInstaller*_x64__8wekyb3d8bbwe\winget.exe" -ErrorAction Stop | Select-Object -ExpandProperty FullName -First 1
}

# 处理winget未找到的情况
if (-not $wingetPath) {
    Write-Host "winget.exe not detected on the device"
    exit 0 # 无winget时默认无需修复,可根据需求调整退出码
}

# 检查指定应用的更新状态,使用应用ID精准匹配
$upgradeResult = & $wingetPath upgrade --id $app_2upgrade --accept-source-agreements 2>&1

# 根据winget返回码判断结果(0=无更新,1=有更新,其他=错误)
switch ($LASTEXITCODE) {
    0 {
        Write-Host "No upgrade available for $app_2upgrade"
        exit 0
    }
    1 {
        Write-Host "Upgrade available for $app_2upgrade"
        exit 1
    }
    default {
        Write-Host "Failed to check updates: $upgradeResult"
        exit 0 # 出错时默认无需修复,可根据需求调整
    }
}

关键修改说明

  • 可靠定位Winget:先用Get-Command从系统PATH中查找winget,兼容性更强;PATH中找不到时,使用SYSTEM账户可访问的WindowsApps路径(包含发布者ID8wekyb3d8bbwe,此路径对SYSTEM开放权限)。
  • 精准更新检测:使用--id参数指定应用ID7zip.7zip,避免模糊字符串匹配的误差,同时添加--accept-source-agreements自动接受源协议,避免交互阻塞。
  • 基于返回码判断状态:Winget的upgrade命令返回码规则明确,比字符串匹配更可靠:
    • 返回码0:无可用更新
    • 返回码1:有可用更新
    • 其他返回码:检测过程出错
  • 错误处理:添加try-catch和空值判断,避免因winget未找到导致脚本崩溃。

内容的提问来源于stack exchange,提问作者Daņiils Poļakovs

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 09:35:15