Files
management-scripts/resources/office/Office-UserCleanup.ps1
T
2026-10-21 09:30:15 -04:00

194 lines
12 KiB
PowerShell

#Requires -Version 5.1
# EmberkomOfficeUserCleanup-v4
# Run only as the affected user, at limited privilege; staged by the Office installer.
param([Parameter(Mandatory = $true)][ValidatePattern('^[a-f0-9]{32}$')][string]$DeploymentId)
function Get-OfficeUserCleanupDefinitions {
# This helper runs independently of Tools.ps1 and the main installer's functions.
@{ MsiBusyAttempts=5; MsiBusyRetrySeconds=15; RegistrationCheckAttempts=13; RegistrationCheckSeconds=5 }
}
function Test-OfficeCredentialTarget {
param([string]$Target)
# Preserve generic Azure AD, WindowsLive, OneDrive and MicrosoftAccount credentials.
$Target -match '^MicrosoftOffice(15|16)(?:_Data:|:)'
}
function Clear-OfficeUserCredentials {
if (!('Emberkom.OfficeCredentials' -as [type])) {
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
namespace Emberkom {
public static class OfficeCredentials {
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct Credential {
public UInt32 Flags, Type;
public string TargetName, Comment;
public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
public UInt32 CredentialBlobSize;
public IntPtr CredentialBlob;
public UInt32 Persist, AttributeCount;
public IntPtr Attributes;
public string TargetAlias, UserName;
}
[DllImport("advapi32.dll", EntryPoint="CredEnumerateW", CharSet=CharSet.Unicode, SetLastError=true)]
public static extern bool Enumerate(string filter, int flags, out int count, out IntPtr credentials);
[DllImport("advapi32.dll", EntryPoint="CredDeleteW", CharSet=CharSet.Unicode, SetLastError=true)]
public static extern bool Delete(string target, UInt32 type, int flags);
[DllImport("advapi32.dll")] public static extern void CredFree(IntPtr buffer);
}
}
'@
}
$count = 0; $pointer = [IntPtr]::Zero
if (![Emberkom.OfficeCredentials]::Enumerate($null, 0, [ref]$count, [ref]$pointer)) {
$errorCode = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
if ($errorCode -eq 1168) { return }
throw "Cannot enumerate user credentials (Win32 $errorCode)."
}
try {
for ($index = 0; $index -lt $count; $index++) {
$entry = [Runtime.InteropServices.Marshal]::ReadIntPtr($pointer, $index * [IntPtr]::Size)
$credential = [Runtime.InteropServices.Marshal]::PtrToStructure($entry, [type][Emberkom.OfficeCredentials+Credential])
if (Test-OfficeCredentialTarget $credential.TargetName) {
if (![Emberkom.OfficeCredentials]::Delete($credential.TargetName, $credential.Type, 0)) { throw 'Could not remove an Office credential.' }
}
}
} finally { [Emberkom.OfficeCredentials]::CredFree($pointer) }
}
function Invoke-OfficeUserUninstaller {
param([string]$Path, [string]$Arguments)
$signature = Get-AuthenticodeSignature -LiteralPath $Path -ErrorAction Stop
if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch '(^|,\s*)O=Microsoft Corporation(,|$)') { throw "Uninstaller is not validly signed by Microsoft: $Path" }
$process = Start-Process -FilePath $Path -ArgumentList $Arguments -WindowStyle Hidden -Wait -PassThru -ErrorAction Stop
if ($process.ExitCode -ne 0) { throw "User app uninstall failed ($($process.ExitCode)): $Path" }
}
function Remove-OfficeUserLegacyTeams {
$teamsRoot = Join-Path $env:LOCALAPPDATA 'Microsoft\Teams'
$teamsUpdater = Join-Path $teamsRoot 'Update.exe'
if (Test-Path -LiteralPath $teamsUpdater) {
Get-Process -Name Teams -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -eq [Diagnostics.Process]::GetCurrentProcess().SessionId } | Stop-Process -Force -ErrorAction Stop
Invoke-OfficeUserUninstaller $teamsUpdater '--uninstall -s'
}
$teamsKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\Teams'
if ((Test-Path -LiteralPath (Join-Path $teamsRoot 'current\Teams.exe')) -or (Test-Path -LiteralPath $teamsKey)) { throw 'Classic Teams remains registered or installed for this user.' }
}
function Test-OfficeUserMsiProduct {
param([Parameter(Mandatory=$true)][ValidatePattern('^\{[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\}$')][string]$ProductCode)
if (!('Emberkom.OfficeUserMsi' -as [type])) {
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
namespace Emberkom {
public static class OfficeUserMsi {
[DllImport("msi.dll", CharSet=CharSet.Unicode, ExactSpelling=true)]
private static extern uint MsiEnumProductsExW(string product, string userSid, uint context, uint index, IntPtr code, IntPtr installedContext, IntPtr sid, IntPtr sidLength);
public static uint Find(string product) {
// Native NULL selects this user; 3 includes managed/unmanaged per-user products only.
return MsiEnumProductsExW(product, null, 3, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
}
}
}
'@
}
$code = [Emberkom.OfficeUserMsi]::Find($ProductCode)
if ($code -eq 0) { return $true }
if ($code -in @(259, 1605)) { return $false }
throw "Cannot determine this user's MSI registration for $ProductCode (Win32 $code)."
}
function Get-OfficeUserTeamsAddinEntries {
# A per-user MSI can have an HKLM uninstall entry. Ask Windows Installer which
# products belong to this user instead of treating the hive as installation scope.
$roots = @('HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall', 'HKCU:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall', 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall', 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall')
$seen = @{}
foreach ($root in $roots) {
if (!(Test-Path -LiteralPath $root)) { continue }
foreach ($entry in @(Get-ItemProperty -Path "$root\*" -ErrorAction Stop | Where-Object { $_.DisplayName -eq 'Microsoft Teams Meeting Add-in for Microsoft Office' -and $_.Publisher -like 'Microsoft*' })) {
if ($seen.ContainsKey($entry.PSChildName)) { continue }
$seen[$entry.PSChildName] = $true
if (Test-OfficeUserMsiProduct $entry.PSChildName) { $entry }
}
}
}
function Remove-OfficeUserCompanions {
param([switch]$PreserveReinstalledApps)
$definitions = Get-OfficeUserCleanupDefinitions
Remove-OfficeUserLegacyTeams
if ($PreserveReinstalledApps) {
Write-Host 'Reinstallation has started. Preserving the Teams meeting add-in and leaving per-user OneDrive migration to the per-machine OneDrive installer.'
return
}
foreach ($entry in @(Get-OfficeUserTeamsAddinEntries)) {
Write-Host "Removing this user's Teams meeting add-in $($entry.DisplayVersion), $($entry.PSChildName)."
for ($attempt = 1; ; $attempt++) {
$process = Start-Process -FilePath "$env:WINDIR\System32\msiexec.exe" -ArgumentList "/x $($entry.PSChildName) /qn /norestart" -WindowStyle Hidden -Wait -PassThru -ErrorAction Stop
if ($process.ExitCode -ne 1618 -or $attempt -ge $definitions.MsiBusyAttempts) { break }
Write-Host "Windows Installer is busy; retrying the user add-in removal in $($definitions.MsiBusyRetrySeconds) seconds (attempt $attempt of $($definitions.MsiBusyAttempts))."
Start-Sleep -Seconds $definitions.MsiBusyRetrySeconds
}
if ($process.ExitCode -notin @(0, 1605, 1614)) { throw "Per-user Teams add-in removal needs attention (exit $($process.ExitCode)), product $($entry.PSChildName)." }
for ($attempt = 1; $attempt -le $definitions.RegistrationCheckAttempts; $attempt++) {
$remains = Test-OfficeUserMsiProduct $entry.PSChildName
if (!$remains -or $attempt -eq $definitions.RegistrationCheckAttempts) { break }
if ($attempt -eq 1) { Write-Host 'Waiting for the user add-in registration to disappear.' }
Start-Sleep -Seconds $definitions.RegistrationCheckSeconds
}
if ($remains) { throw "Teams meeting add-in $($entry.PSChildName) remains registered for this user." }
}
$oneDriveKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\OneDriveSetup.exe'
if (Test-Path -LiteralPath $oneDriveKey) {
$uninstall = (Get-ItemProperty -LiteralPath $oneDriveKey -ErrorAction Stop).UninstallString
$match = [regex]::Match($uninstall, '^\s*"([^"\r\n]+\\OneDriveSetup\.exe)"\s+/uninstall\s*$', 'IgnoreCase')
if (!$match.Success) { throw 'Unexpected per-user OneDrive uninstall command.' }
$exe = [IO.Path]::GetFullPath($match.Groups[1].Value)
$roots = @((Join-Path $env:LOCALAPPDATA 'Microsoft\OneDrive'), (Join-Path $env:WINDIR 'System32'), (Join-Path $env:WINDIR 'SysWOW64'))
$allowed = @($roots | Where-Object { $exe.StartsWith([IO.Path]::GetFullPath($_).TrimEnd('\') + '\', [StringComparison]::OrdinalIgnoreCase) }).Count -gt 0
if (!$allowed) { throw 'Per-user OneDrive uninstaller is outside supported locations.' }
Get-Process -Name OneDrive -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -eq [Diagnostics.Process]::GetCurrentProcess().SessionId } | Stop-Process -Force -ErrorAction Stop
Invoke-OfficeUserUninstaller $exe '/uninstall'
if (Test-Path -LiteralPath $oneDriveKey) { throw 'OneDrive remains registered for this user.' }
}
if (Test-Path -LiteralPath (Join-Path $env:LOCALAPPDATA 'Microsoft\OneDrive\OneDrive.exe')) { throw 'A per-user OneDrive binary remains. Repair/uninstall that installation, then retry user cleanup.' }
}
function Invoke-OfficeUserCleanup {
param([string]$Workspace)
if (!(Test-Path -LiteralPath (Join-Path $Workspace 'user-cleanup.lock') -PathType Leaf)) { throw 'User cleanup lock file is missing.' }
$deadline = [DateTime]::UtcNow.AddMinutes(5); $lock = $null
do {
try { $lock = [IO.File]::Open((Join-Path $Workspace 'user-cleanup.lock'), [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None) }
catch [IO.IOException] { if ([DateTime]::UtcNow -ge $deadline) { throw 'Another user cleanup is still active; retry at the next sign-in.' }; Start-Sleep -Seconds 2 }
} while ($null -eq $lock)
try {
Clear-OfficeUserCredentials
$preserve = Test-Path -LiteralPath (Join-Path $Workspace 'reinstall-started')
Remove-OfficeUserCompanions -PreserveReinstalledApps:$preserve
} finally { $lock.Dispose() }
}
$ErrorActionPreference = 'Stop'
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
if ($identity.IsSystem -or $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'User cleanup requires a limited user token, not SYSTEM or an elevated administrator.' }
$marker = "HKCU:\Software\Emberkom\OfficeDeployment\$DeploymentId"
if ((Get-ItemPropertyValue -LiteralPath $marker -Name Status -ErrorAction SilentlyContinue) -eq 'Complete') { exit 0 }
$logFolder = Join-Path $env:LOCALAPPDATA 'Emberkom\OfficeDeployment'
$null = New-Item -ItemType Directory -Path $logFolder -Force
$null = Start-Transcript -Path (Join-Path $logFolder "$DeploymentId.log") -Append
try {
$null = New-Item -Path $marker -Force
Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Running'
Invoke-OfficeUserCleanup -Workspace $PSScriptRoot
Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Complete'
} catch {
Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Failed'
Write-Error $_ -ErrorAction Continue
exit 1
} finally { $null = Stop-Transcript }