Files
management-scripts/resources/office/Office-UserCleanup.ps1
T

141 lines
8.6 KiB
PowerShell

#Requires -Version 5.1
# EmberkomOfficeUserCleanup-v2
# 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 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 Remove-OfficeUserCompanions {
param([switch]$PreserveReinstalledApps)
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
}
$uninstallRoot = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall'
if (Test-Path -LiteralPath $uninstallRoot) {
foreach ($entry in @(Get-ItemProperty -Path "$uninstallRoot\*" -ErrorAction Stop | Where-Object { $_.DisplayName -eq 'Microsoft Teams Meeting Add-in for Microsoft Office' -and $_.Publisher -like 'Microsoft*' })) {
if ($entry.PSChildName -notmatch '^\{[0-9A-Fa-f-]{36}\}$') { throw 'Unexpected per-user Teams add-in product code.' }
$process = Start-Process -FilePath "$env:WINDIR\System32\msiexec.exe" -ArgumentList "/x $($entry.PSChildName) /qn /norestart" -WindowStyle Hidden -Wait -PassThru -ErrorAction Stop
if ($process.ExitCode -notin @(0, 1605, 1614)) { throw "Per-user Teams add-in removal needs attention (exit $($process.ExitCode))." }
if (Test-Path -LiteralPath $entry.PSPath) { throw 'Per-user Teams meeting add-in remains registered.' }
}
}
$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 }