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

通过PowerShell卸载所有用户的MS Teams个人版并阻止新用户安装

关于卸载MS Teams(个人版)PowerShell代码的修正与优化建议

现有代码的问题

  1. 变量$uninstall_Teams_Free的定义在调用逻辑之后,执行时会因变量未初始化直接报错
  2. Get-Process -Name "msteams"在无对应进程时会抛出错误,缺少错误抑制处理
  3. 仅卸载已安装的Appx包,未处理系统预部署包,新用户登录后仍会自动安装Teams
  4. 未清理用户本地的Teams缓存残留文件,可能导致残留图标或配置

修正后的完整代码

# 注意:需以管理员身份运行此脚本

# 提前定义卸载核心逻辑
$uninstall_Teams_Free = {
    # 卸载所有用户已安装的Teams Appx包
    Get-AppxPackage -Name MicrosoftTeams -AllUsers | Remove-AppxPackage -AllUsers -ErrorAction SilentlyContinue
    Start-Sleep -Seconds 3

    # 移除系统预部署包,彻底阻止新用户自动安装
    Get-AppxProvisionedPackage -Online | Where-Object { $_.DisplayName -eq "MicrosoftTeams" } | Remove-AppxProvisionedPackage -Online -ErrorAction SilentlyContinue
    Start-Sleep -Seconds 3
}

# 检查Teams是否已安装
if (Get-AppxPackage -Name MicrosoftTeams -ErrorAction SilentlyContinue) {
    # 静默终止Teams进程(如果存在)
    Get-Process -Name "msteams" -ErrorAction SilentlyContinue | Stop-Process -Force
    Start-Sleep -Seconds 3

    # 执行卸载操作
    & $uninstall_Teams_Free
}

# 清理所有用户本地的Teams缓存残留
$userProfiles = Get-ChildItem -Path "C:\Users" -Directory
foreach ($profile in $userProfiles) {
    $teamsCachePath = Join-Path -Path $profile.FullName -ChildPath "AppData\Local\Microsoft\Teams"
    if (Test-Path -Path $teamsCachePath) {
        Remove-Item -Path $teamsCachePath -Recurse -Force -ErrorAction SilentlyContinue
    }
}

# 可选:验证卸载结果
if (-not (Get-AppxPackage -Name MicrosoftTeams -ErrorAction SilentlyContinue) -and -not (Get-AppxProvisionedPackage -Online | Where-Object DisplayName -eq "MicrosoftTeams" -ErrorAction SilentlyContinue)) {
    Write-Host "MS Teams(个人版)已成功卸载并阻止新用户自动安装" -ForegroundColor Green
} else {
    Write-Host "卸载未完全成功,请检查权限或手动清理" -ForegroundColor Red
}

实用技巧与补充建议

  • 强制管理员权限:脚本开头可添加权限检测逻辑,自动提升权限:
    if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
        Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs
        exit
    }
    
  • 处理MSI版本Teams:如果Teams是通过MSI安装(而非Appx),需额外执行:
    Get-WmiObject -Class Win32_Product | Where-Object { $_.Name -match "Microsoft Teams" } | ForEach-Object { $_.Uninstall() }
    
  • 缩短休眠时间:3秒足够等待进程终止和卸载操作完成,无需5秒,可提升脚本执行效率
  • 错误抑制必要性:全程添加-ErrorAction SilentlyContinue可避免无意义的报错(比如进程不存在、缓存文件夹已删除等场景)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 11:14:54