-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntune-Win32-PowerShell-Script-Installer-Template-Uninstall.ps1
More file actions
265 lines (233 loc) · 10.3 KB
/
Intune-Win32-PowerShell-Script-Installer-Template-Uninstall.ps1
File metadata and controls
265 lines (233 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
<#
.SYNOPSIS
Intune Win32 app PowerShell script installer template - Uninstall.
.DESCRIPTION
Uninstalls applications via Intune Win32 PowerShell script installer.
Supports MSI/EXE, file removal, and registry cleanup.
SYSTEM context: removes HKCU/user files from ALL profiles.
User context: removes from current user only.
.NOTES
Author: Martin Bengtsson | imab.dk
Version: 1.5
History:
1.5 - Added process architecture and script hash logging
1.4 - HKU enumeration for registry operations, single-quoted config paths,
ExpandString for user-context expansion, strict SID regex
1.3 - Added $env:USERPROFILE translation, $env:ProgramW6432 admin check,
fixed non-user paths looping through all profiles when running as SYSTEM
1.2 - Added admin detection, file removal and registry cleanup support
1.0 - Initial release
#>
# === Configuration ===
# --- App Identity ---
[string]$AppName = "Notepad++"
[string]$LogFile = "$env:ProgramData\Microsoft\IntuneManagementExtension\Logs\$AppName-Uninstall.log"
# --- Step 1: Uninstaller ---
[string]$UninstallerFile = "npp.8.9.1.Installer.x64.msi"
[string]$UninstallerArgs = "/qn /norestart"
[int[]]$SuccessExitCodes = @(0, 3010)
# Examples:
# MSI: "/qn /norestart"
# EXE: "/S" or "/silent" or "/VERYSILENT /SUPPRESSMSGBOXES"
# --- Step 2: Remove Files ---
# Full path(s) to files to remove
# Use single quotes for $env: paths to preserve variable names for per-user expansion
# SYSTEM context: $env:APPDATA/$env:LOCALAPPDATA/$env:USERPROFILE paths are applied to all user profiles
$FilesToRemove = @(
'$env:APPDATA\Notepad++\imabdk-config.json'
'$env:ProgramW6432\Notepad++\imabdk-config.json'
# '$env:LOCALAPPDATA\MyApp\settings.xml'
)
# --- Step 3: Remove Registry Settings ---
# Action: "DeleteValue" or "DeleteKey" (removes entire key)
# SYSTEM context: HKCU paths are applied to all user profiles
$RegistryRemovals = @(
@{ Path = "HKLM:\SOFTWARE\imab.dk"; Action = "DeleteKey" }
@{ Path = "HKCU:\SOFTWARE\imab.dk"; Action = "DeleteKey" }
# Remove a single value instead of the entire key:
# @{ Path = "HKCU:\SOFTWARE\imab.dk"; Name = "UserSetting"; Action = "DeleteValue" }
)
# === Runtime Detection ===
$script:IsSystem = ([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value -eq "S-1-5-18")
$script:IsAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
#region Functions
# Tests if path requires administrator privileges
function Test-RequiresAdmin {
param([string]$Path)
if ($Path -match "^HKLM:|^Registry::HKEY_LOCAL_MACHINE") { return $true }
$adminPaths = @($env:ProgramFiles, ${env:ProgramFiles(x86)}, $env:ProgramW6432, $env:SystemRoot, $env:ProgramData)
foreach ($adminPath in $adminPaths) {
if ($adminPath -and $Path -like "$adminPath*") { return $true }
}
return $false
}
# Gets all user profiles (AD and Entra ID) - used for file operations
function Get-UserProfiles {
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\*" |
Where-Object { $_.PSChildName -match "^S-1-(5-21|12-1)-" -and (Test-Path $_.ProfileImagePath) }
}
# Gets user SIDs with loaded registry hives - used for registry operations
function Get-UserSIDs {
(Get-ChildItem "Registry::HKEY_USERS" -ErrorAction SilentlyContinue).PSChildName |
Where-Object { $_ -match '^S-1-(5-21|12-1)-\d+-\d+-\d+-\d+$' }
}
# Writes to console and log file
function Write-Log {
param(
[string]$Message,
[int]$MaxLogSizeMB = 5
)
Write-Output "[$AppName] [UNINSTALL] $Message"
if ([string]::IsNullOrWhiteSpace($Message)) { return }
try {
if ((Test-Path $LogFile) -and ((Get-Item $LogFile).Length / 1MB) -ge $MaxLogSizeMB) {
Move-Item -Path $LogFile -Destination "$LogFile.old" -Force -ErrorAction SilentlyContinue
}
Add-Content -Path $LogFile -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') [$AppName] [UNINSTALL] $Message" -ErrorAction SilentlyContinue
}
catch { }
}
# Uninstalls application using MSI or EXE
function Uninstall-Application {
param (
[Parameter(Mandatory)]
[string]$UninstallerPath,
[string]$Arguments,
[int[]]$SuccessCodes = @(0, 3010)
)
$uninstallerExt = [System.IO.Path]::GetExtension($UninstallerPath).ToLower()
if (-not (Test-Path -Path $UninstallerPath)) {
throw "Uninstaller not found: $UninstallerPath"
}
switch ($uninstallerExt) {
".msi" {
$msiLogPath = "$env:ProgramData\Microsoft\IntuneManagementExtension\Logs\$AppName-MSI-Uninstall.log"
$msiArgs = "/x `"$UninstallerPath`" $Arguments /l*v `"$msiLogPath`""
Write-Log "Uninstalling MSI: msiexec.exe $msiArgs"
$process = Start-Process -FilePath "msiexec.exe" -ArgumentList $msiArgs -Wait -PassThru
}
".exe" {
Write-Log "Uninstalling EXE: $UninstallerPath $Arguments"
$process = Start-Process -FilePath $UninstallerPath -ArgumentList $Arguments -Wait -PassThru
}
default {
throw "Unsupported uninstaller type: $uninstallerExt"
}
}
Write-Log "Uninstaller finished with exit code: $($process.ExitCode)"
if ($process.ExitCode -notin $SuccessCodes) {
throw "Uninstallation failed with exit code: $($process.ExitCode)"
}
}
# Removes files (SYSTEM: from all profiles, User: current only)
function Remove-FilesFromDestination {
param (
[array]$Files
)
if ($script:IsSystem) {
$userProfilePaths = Get-UserProfiles | Select-Object -ExpandProperty ProfileImagePath
}
foreach ($file in $Files) {
$isUserPath = $file -match '\$env:(APPDATA|LOCALAPPDATA|USERPROFILE)'
if ($script:IsSystem -and $isUserPath) {
Write-Log "Removing from $($userProfilePaths.Count) user profile(s)"
foreach ($profilePath in $userProfilePaths) {
# Translate user-specific environment paths to actual profile paths
$filePath = $file `
-replace '\$env:APPDATA', "$profilePath\AppData\Roaming" `
-replace '\$env:LOCALAPPDATA', "$profilePath\AppData\Local" `
-replace '\$env:USERPROFILE', "$profilePath"
if (Test-Path -Path $filePath) {
Remove-Item -Path $filePath -Force
Write-Log "Removed: $filePath"
}
}
}
else {
$filePath = $ExecutionContext.InvokeCommand.ExpandString($file)
if ((Test-RequiresAdmin -Path $filePath) -and -not $script:IsAdmin) {
throw "Access denied: '$filePath' requires administrator privileges"
}
if (Test-Path -Path $filePath) {
Remove-Item -Path $filePath -Force
Write-Log "Removed: $filePath"
}
}
}
}
# Removes registry values/keys (SYSTEM: from all profiles, User: current only)
function Remove-RegistrySettings {
param (
[Parameter(Mandatory)]
[array]$Settings
)
$userSIDs = if ($script:IsSystem) { Get-UserSIDs } else { $null }
if ($userSIDs) {
Write-Log "Running as SYSTEM - removing from $(@($userSIDs).Count) user(s)"
}
foreach ($setting in $Settings) {
$paths = @()
if ($setting.Path -like "HKCU:\*" -and $script:IsSystem) {
if (-not $userSIDs) {
Write-Log "No user hives loaded - skipping HKCU settings"
continue
}
foreach ($sid in $userSIDs) {
$paths += $setting.Path -replace "^HKCU:\\", "Registry::HKEY_USERS\$sid\"
}
}
else {
if ((Test-RequiresAdmin -Path $setting.Path) -and -not $script:IsAdmin) {
throw "Access denied: '$($setting.Path)' requires administrator privileges"
}
$paths += $setting.Path
}
foreach ($regPath in $paths) {
switch ($setting.Action) {
"DeleteValue" {
if (Test-Path $regPath) {
Remove-ItemProperty -Path $regPath -Name $setting.Name -Force -ErrorAction SilentlyContinue
Write-Log "Removed value: $regPath\$($setting.Name)"
}
}
"DeleteKey" {
if (Test-Path $regPath) {
Remove-Item -Path $regPath -Recurse -Force -ErrorAction SilentlyContinue
Write-Log "Removed key: $regPath"
}
}
}
}
}
}
#endregion
#region Main
Write-Log "=== Starting uninstallation of $AppName ==="
Write-Log "Running as: $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)"
Write-Log "Context: $(if ($script:IsSystem) { 'SYSTEM' } else { 'User' }), Admin: $($script:IsAdmin)"
Write-Log "Process: $(if ([Environment]::Is64BitProcess) { '64-bit' } else { '32-bit (WOW64 - registry writes will be redirected!)' }), OS: $(if ([Environment]::Is64BitOperatingSystem) { '64-bit' } else { '32-bit' })"
Write-Log "Script hash: $((Get-FileHash -Path $PSCommandPath -Algorithm MD5).Hash.Substring(0,8))"
Write-Log "Script path: $PSScriptRoot"
try {
# --- Step 1: Uninstall application ---
Write-Log "--- Step 1: Uninstalling application ---"
$uninstallerPath = if ([System.IO.Path]::IsPathRooted($UninstallerFile)) { $UninstallerFile } else { Join-Path -Path $PSScriptRoot -ChildPath $UninstallerFile }
Uninstall-Application -UninstallerPath $uninstallerPath -Arguments $UninstallerArgs -SuccessCodes $SuccessExitCodes
# --- Step 2: Remove configuration files ---
if ($FilesToRemove.Count -gt 0) {
Write-Log "--- Step 2: Removing configuration files ---"
Remove-FilesFromDestination -Files $FilesToRemove
}
# --- Step 3: Remove registry settings ---
if ($RegistryRemovals.Count -gt 0) {
Write-Log "--- Step 3: Removing registry settings ---"
Remove-RegistrySettings -Settings $RegistryRemovals
}
Write-Log "=== Uninstallation of $AppName completed successfully ==="
exit 0
}
catch {
Write-Log "=== Uninstallation of $AppName failed: $($_.Exception.Message) ==="
exit 1
}
#endregion