-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathisoDebloaterScript.ps1
More file actions
1772 lines (1609 loc) · 103 KB
/
isoDebloaterScript.ps1
File metadata and controls
1772 lines (1609 loc) · 103 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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Windows ISO Debloater
# Author: itsNileshHere
# Date: 2023-11-21
# Description: A simple PSscript to modify windows iso file. For more info check README.md
param(
[switch]$noPrompt,
[string]$isoPath = "",
[string]$winEdition = "",
[string]$outputISO = "",
[ValidateSet("yes", "no")]$useDISM = "",
[ValidateSet("yes", "no")]$AppxRemove = "",
[ValidateSet("yes", "no")]$CapabilitiesRemove = "",
[ValidateSet("yes", "no")]$OnedriveRemove = "",
[ValidateSet("yes", "no")]$EDGERemove = "",
[ValidateSet("yes", "no")]$AIRemove = "",
[ValidateSet("yes", "no")]$TPMBypass = "",
[ValidateSet("yes", "no")]$UserFoldersEnable = "",
[ValidateSet("yes", "no")]$DriverIntegrate = "",
[ValidateSet("yes", "no")]$ESDConvert = "",
[ValidateSet("yes", "no")]$useOscdimg = ""
)
# If -noPrompt is used, ensure required parameters are provided
if ($noPrompt) {
$missing = @("isoPath","winEdition","outputISO") | Where-Object { [string]::IsNullOrWhiteSpace((Get-Variable $_).Value) }
if ($missing) { Write-Error "When using -noPrompt, these parameters are required: $($missing -join ', ')"; Exit 1 }
}
# Disable Pause if -noprompt is used
if ($noPrompt) { function Pause { } }
# Administrator Privileges
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Host "This script must be run as Administrator. Re-launching with elevated privileges..." -ForegroundColor Yellow
# Resolve relative paths before relaunching
if ($isoPath -and -not [System.IO.Path]::IsPathRooted($isoPath)) {
$isoPath = Join-Path -Path $PSScriptRoot -ChildPath $isoPath | Resolve-Path -ErrorAction SilentlyContinue
if (-not $isoPath) {
$isoPath = Join-Path -Path (Get-Location).Path -ChildPath $PSBoundParameters['isoPath']
if (Test-Path $isoPath) {
$isoPath = (Get-Item $isoPath).FullName
}
}
}
if ($outputISO -and -not [System.IO.Path]::IsPathRooted($outputISO)) {
$outputISO = Join-Path -Path (Get-Location).Path -ChildPath $outputISO
$outputISO = [System.IO.Path]::GetFullPath($outputISO)
}
$params = @()
$PSBoundParameters.GetEnumerator() | ForEach-Object {
if ($_.Value -is [switch] -and $_.Value) { $params += "-$($_.Key)" }
elseif ($_.Value -is [string] -and $_.Value) {
# Use resolved paths for isoPath and outputISO
if ($_.Key -eq 'isoPath' -and $isoPath) { $params += "-$($_.Key)", "`"$isoPath`"" }
elseif ($_.Key -eq 'outputISO' -and $outputISO) { $params += "-$($_.Key)", "`"$outputISO`"" }
else { $params += "-$($_.Key)", "`"$($_.Value)`"" }
}
}
$argss = "-NoProfile -ExecutionPolicy Bypass -File `"$($MyInvocation.MyCommand.Path)`" $($params -join ' ')"
if (Get-Command wt -ErrorAction SilentlyContinue) { Start-Process wt "PowerShell $argss" -Verb RunAs }
else { Start-Process PowerShell $argss -Verb RunAs }
Exit
}
Clear-Host
$asciiArt = @"
_ ___ __ _________ ____ ____ __ __ __
| | / (_)___ ____/ /___ _ _______ / _/ ___// __ \ / __ \___ / /_ / /___ ____ _/ /____ _____
| | /| / / / __ \/ __ / __ \ | /| / / ___/ / / \__ \/ / / / / / / / _ \/ __ \/ / __ \/ __ `/ __/ _ \/ ___/
| |/ |/ / / / / / /_/ / /_/ / |/ |/ (__ ) _/ / ___/ / /_/ / / /_/ / __/ /_/ / / /_/ / /_/ / /_/ __/ /
|__/|__/_/_/ /_/\__,_/\____/|__/|__/____/ /___//____/\____/ /_____/\___/_.___/_/\____/\__,_/\__/\___/_/
-By itsNileshHere
"@
Write-Host $asciiArt -ForegroundColor Cyan
Start-Sleep -Milliseconds 1000
Write-Host "Starting Windows ISO Debloater Script..." -ForegroundColor Green
Start-Sleep -Milliseconds 800
Write-Host "`n*Important Notes: " -ForegroundColor Yellow
Write-Host " 1. Some prompts will appear during the process."
Write-Host " 2. Administrative privileges are required to run this script."
Write-Host " 3. Review the script beforehand to understand its actions."
Write-Host " 4. To whitelist a package, open the script and comment out the corresponding Packagename."
Write-Host " 5. Select the ISO to proceed."
Start-Sleep -Milliseconds 800
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
$PSDefaultParameterValues['*:Encoding'] = 'utf8'
$scriptDirectory = "$PSScriptRoot"
$logFilePath = Join-Path -Path $scriptDirectory -ChildPath 'script_log.txt' # Log File Path
$transcript = "$env:TEMP\transcript_$(Get-Random).txt" # Start Transcript
Start-Transcript $transcript -Append -ErrorAction SilentlyContinue 2>&1 | Out-Null
# Get system information
$osInfo = Get-WmiObject -Class Win32_OperatingSystem
$logEntry = @"
$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - Script started
- Launched As: $((Get-CimInstance Win32_Process -Filter "ProcessId = $PID").CommandLine)
- Windows Version: $($osInfo.Caption) $($osInfo.Version) (Build $($osInfo.BuildNumber))
- System Architecture: $($osInfo.OSArchitecture)
- Install Date: $([Management.ManagementDateTimeConverter]::ToDateTime($osInfo.InstallDate).ToString())
- System Language: $((Get-Culture).DisplayName)
- Default Language: $((Get-UICulture).DisplayName)
- Windows Directory: $($env:windir)`n
"@
# Initialize log file
$logEntry | Out-File -FilePath $logFilePath -Append
# Function to write logs
function Write-Log {
[CmdletBinding()]
param ([Parameter(ValueFromPipeline=$true)][object]$InputObj, [string]$msg, [switch]$Raw, [string]$Sep = " || ")
process {
$content = if ($msg) { $msg } elseif ($null -ne $InputObj) { if ($InputObj -is [string]) { $InputObj } else { $InputObj | Out-String } } else { return }
if (-not $Raw -and ($content = $content.Trim())) {
$lines = @($content -split '\n' | Where-Object { $_.Trim() })
$cut = $lines | Where-Object { $_ -match '^\s*\+\s*(CategoryInfo|FullyQualifiedErrorId)\s*:' } | Select-Object -First 1
if ($cut) { $lines = $lines[0..($lines.IndexOf($cut) - 1)] }
if ($lines.Count -gt 1) {
$processedLines = foreach ($line in $lines) {
$trimmed = $line.Trim()
if ($trimmed -match '^At\s+(.+)') { "At $($matches[1])" }
elseif ($trimmed -match '^\s*\+\s*~+') { continue } # Skip underline line
elseif ($trimmed -match '^\s*\+\s*(.+)') { "+ " + ($matches[1] -replace '\s{2,}', ' ') }
elseif ($trimmed -match '^\s*\+?\s*(\w+\w+)\s*:\s*(.+)') { "$($matches[1]): $($matches[2])" }
elseif ($trimmed -notmatch '^-{4,}' -and $trimmed) { $trimmed -replace '\s{2,}', ' ' }
}
$content = $processedLines -join $Sep
} else { $content = $content -replace '\s{2,}', ' ' }
}
if ($content) { Add-Content -Path "$logFilePath" -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $content" }
}
}
# Function to invoke DISM commands if powershell fails
function Invoke-DismFailsafe {
param([scriptblock]$PS, [scriptblock]$Dism)
if ($useDISM -ieq "yes") {
& $Dism 2>&1 | Write-Log
} else {
try { & $PS 2>&1 | Write-Log } catch { & $Dism 2>&1 | Write-Log }
}
}
# Confirmation Function
function Get-Confirmation {
param([string]$Question, [bool]$DefaultValue = $true, [string]$Description = "")
$defaultText = if ($DefaultValue) { "Y" } else { "N" }
$optionsText = if ($DefaultValue) { "Y/n" } else { "y/N" }
do {
Write-Host "$Question" -ForegroundColor Cyan -NoNewline
if ($Description) { Write-Host " - $Description" -ForegroundColor DarkGray -NoNewline }
Write-Host " ($optionsText): " -ForegroundColor White -NoNewline
$answer = Read-Host
if ([string]::IsNullOrWhiteSpace($answer)) {
Write-Host "Using default: $defaultText" -ForegroundColor Yellow
return $DefaultValue
}
$answer = $answer.ToUpper()
if ($answer -eq 'Y') { return $true }
if ($answer -eq 'N') { return $false }
Write-Warning "Invalid input. Enter 'Y' for Yes, 'N' for No, or Enter for default ($defaultText)."
} while ($true)
}
# Parameter Value Validation Function
function Get-ParameterValue {
param( [string]$ParameterValue, [bool]$DefaultValue, [string]$Question, [string]$Description )
if ($ParameterValue -ne "") { return $ParameterValue -eq "yes" }
if ($noPrompt) { return $DefaultValue }
# If neither noPrompt nor param was provided, prompt the user
return Get-Confirmation -Question $Question -DefaultValue $DefaultValue -Description $Description
}
# Cleanup Function
function Remove-TempFiles {
Remove-Item -Path $destinationPath -Recurse -Force 2>&1 | Write-Log
Remove-Item -Path $installMountDir -Recurse -Force 2>&1 | Write-Log
Remove-Item -Path "$env:SystemDrive\WIDTemp" -Recurse -Force 2>&1 | Write-Log
Stop-Transcript 2>&1 | Write-Log
$content = Get-Content $transcript | Where-Object { $_ -notmatch "^(Windows PowerShell transcript|Start time:|Username:|RunAs User:|Configuration|Host Application:|Process ID:|PS[A-Z]|BuildVersion:|CLRVersion:|WSManStackVersion:|SerializationVersion:|Transcript started|PS C:\\|^\*{10,}|End time:)" -and $_.Trim() }
Add-Content $logFilePath -Value ("`n" + "="*50 + "`nTerminal Snapshot - $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" + "`n" + "="*50 + "`n" + ($content -join "`n"))
Remove-Item $transcript -Force 2>&1 | Write-Log
}
# Set Ownership Permissions
function Set-Ownership {
param([string]$Path, [string[]]$Registry)
if ($Path) {
try {
$FullPath = [System.IO.Path]::GetFullPath($Path)
if (-not (Test-Path -Path $FullPath)) { return $true }
$IsFolder = (Get-Item $FullPath).PSIsContainer
# Try ACL method
try {
$Acl = Get-Acl $FullPath
$Acl.SetOwner([System.Security.Principal.NTAccount]"Administrators")
$CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($CurrentUser, "FullControl", $(if ($IsFolder) {"ContainerInherit,ObjectInherit"} else {"None"}), "None", "Allow")
$Acl.SetAccessRule($AccessRule)
Set-Acl -Path $FullPath -AclObject $Acl
if ($IsFolder) { Get-ChildItem -Path $FullPath -Recurse -Force -ErrorAction SilentlyContinue | ForEach-Object {
try { $ChildAcl = Get-Acl $_.FullName
$ChildAcl.SetOwner([System.Security.Principal.NTAccount]"Administrators")
$ChildAcl.SetAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule($CurrentUser, "FullControl", "Allow")))
Set-Acl -Path $_.FullName -AclObject $ChildAcl
}
catch {}
}
}
Write-Log -msg "[ACL] Set ownership for: $FullPath"
return $true
}
# Fallback to icals
catch { Write-Log -msg "ACL method failed for: $FullPath"
try {
& icacls.exe "$FullPath" /setowner "Administrators" /T /C 2>&1 | Out-Null
& icacls.exe "$FullPath" /grant "${CurrentUser}:(F)" /T /C 2>&1 | Out-Null
& icacls.exe "$FullPath" /grant "Administrators:(F)" /T /C 2>&1 | Out-Null
Write-Log -msg "[icacls] Set ownership for: $FullPath"
return $true
}
catch { Write-Log -msg "icacls fallback failed for: $FullPath - $($_.Exception.Message)"; return $false }
}
}
catch { Write-Log -msg "Failed to own path: $Path - $($_.Exception.Message)"; return $false }
}
if ($Registry) {
try {
$sid = (New-Object System.Security.Principal.NTAccount("BUILTIN\Administrators")).Translate([System.Security.Principal.SecurityIdentifier])
$rule = New-Object System.Security.AccessControl.RegistryAccessRule("Administrators", "FullControl", "ContainerInherit", "None", "Allow")
foreach ($keyPath in $Registry) {
try {
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($keyPath, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, [System.Security.AccessControl.RegistryRights]::TakeOwnership)
if ($key) { $acl = $key.GetAccessControl()
$acl.SetOwner($sid)
$key.SetAccessControl($acl)
$key.Close()
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($keyPath, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, [System.Security.AccessControl.RegistryRights]::ChangePermissions)
if ($key) { $acl = $key.GetAccessControl()
$acl.SetAccessRule($rule)
$key.SetAccessControl($acl)
$key.Close()
Write-Log -msg "Set ownership for registry: $keyPath"
}
} else { Write-Log -msg "Unable to open reg-key: $keyPath" }
} catch {}
}
return $true
} catch { Write-Log -msg "Failed to own reg-key: $($_.Exception.Message)"; return $false }
}
return $false
}
# Force Remove Function
function Set-OwnAndRemove {
param([Parameter(Mandatory=$true)][string]$Path)
try {
$FullPath = [System.IO.Path]::GetFullPath($Path)
if (-not (Test-Path -Path $FullPath)) { return $true }
try {
$ownershipResult = Set-Ownership -Path $Path
if (-not $ownershipResult) { throw "ACL method failed" }
Remove-Item -Path $FullPath -Force -Recurse -ErrorAction Stop
Write-Log -msg "Removed with ACL: $FullPath"
return $true
} catch {
Write-Log -msg "ACL method failed for: $FullPath"
try {
$IsFolder = (Get-Item $FullPath -ErrorAction Stop).PSIsContainer
$CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
if($IsFolder) { takeown /F "$FullPath" /R /D Y 2>&1 | Write-Log }
else { takeown /F "$FullPath" /A 2>&1 | Write-Log }
foreach ($Perm in @("*S-1-5-32-544:F", "System:F", "Administrators:F", "$CurrentUser`:F")) {
try {
if($IsFolder) { icacls "$FullPath" /grant:R "$Perm" /T /C 2>&1 | Write-Log }
else { icacls "$FullPath" /grant:R "$Perm" 2>&1 | Write-Log }
if ($LASTEXITCODE -eq 0) { break }
} catch { continue }
}
Remove-Item -Path $FullPath -Force -Recurse -ErrorAction Stop
Write-Log -msg "Removed with icacls: $FullPath"
return $true
} catch { Write-Log -msg "Failed to remove: $FullPath - $($_.Exception.Message)"; return $false }
}
} catch { Write-Log -msg "Error processing path: $Path - $($_.Exception.Message)"; return $false }
}
# Function to check internet connection
function Test-InternetConnection {
param (
[int]$maxAttempts = 3,
[int]$retryDelay = 5,
[string]$hostname = "1.1.1.1", # Cloudflare DNS
[int]$port = 53,
[int]$timeout = 5000
)
for ($attempt = 1; $attempt -le $maxAttempts; $attempt++) {
try {
$client = [Net.Sockets.TcpClient]::new()
if ($client.ConnectAsync($hostname, $port).Wait($timeout)) {
$client.Close(); return $true
}
$client.Close()
} catch {}
Write-Host "Internet connection not available, Trying in $retryDelay seconds..."
Start-Sleep -Seconds $retryDelay
}
Write-Host "`nInternet connection not available after $maxAttempts attempts." -ForegroundColor Red
Write-Host "A working internet connection is required to download oscdimg.exe."
Write-Host "Check your connection and try again."
while ($true) {
$internetChoice = Read-Host -Prompt "`nPress 't' to try again or 'q' to quit"
switch ($internetChoice.ToLower()) {
't' { return Test-InternetConnection @PSBoundParameters }
'q' {
Remove-TempFiles
Exit
}
default { Write-Host "Invalid input. Enter 't' or 'q'." }
}
}
}
# Image Info Function
function Get-WimDetails {
param ( [Parameter(Mandatory = $true)][string]$MountPath )
try {
$out = dism /Image:$MountPath /Get-Intl /English | Out-String
Write-Log -msg "DISM Output for Get-WimDetails:`n$out"
$buildMatch = [regex]::Match($out, "Image Version: \d+\.\d+\.(\d+)\.\d+")
$langMatch = [regex]::Match($out, "(?i)Default\s+system\s+UI\s+language\s*:\s*([a-z]{2}-[A-Z]{2})")
[PSCustomObject]@{
BuildNumber = if ($buildMatch.Success) { $buildMatch.Groups[1].Value } else { $null }
Language = if ($langMatch.Success) { $langMatch.Groups[1].Value } else { $null }
}
}
catch {
Write-Host "Failed to get WIM info: $($_.Exception.Message)" -ForegroundColor Red
return $null
}
}
# Get Image Index Function
function Get-ImageIndex {
param ( [Parameter(Mandatory = $true)][string]$ImagePath )
try {
$out = & dism.exe /get-wiminfo /wimfile:$ImagePath /english 2>$null
Write-Log -msg "DISM Output for Get-ImageIndex:`n$out"
if ($LASTEXITCODE -ne 0) { throw "DISM failed to read image file: $ImagePath" }
$images = @()
$indexPattern = "Index\s*:\s*(\d+)"
$namePattern = "Name\s*:\s*(.+)"
for ($i = 0; $i -lt $out.Count; $i++) {
if ($out[$i] -match $indexPattern) {
$index = $matches[1]
for ($j = $i + 1; $j -lt [Math]::Min($i + 5, $out.Count); $j++) {
if ($out[$j] -match $namePattern) {
$name = $matches[1].Trim()
$images += [PSCustomObject]@{
Index = [int]$index
ImageName = $name
}
break
}
}
}
}
return $images
}
catch {
Write-Log -msg "Failed to get image information: $($_.Exception.Message)"
return $null
}
}
# Oscdimg Path
$OscdimgPath = "$env:SystemDrive\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Deployment Tools\amd64\Oscdimg"
$Oscdimg = Join-Path -Path $OscdimgPath -ChildPath 'oscdimg.exe'
# Autounattend.xml Path
$autounattendXmlPath = Join-Path -Path $scriptDirectory -ChildPath "Autounattend.xml"
# Download Autounattend.xml if not exists
if (-not (Test-Path $autounattendXmlPath)) {
$ProgressPreference = 'SilentlyContinue'
try { Invoke-WebRequest "https://itsnileshhere.github.io/Windows-ISO-Debloater/autounattend.xml" -OutFile $autounattendXmlPath -UseBasicParsing }
catch { Write-Log -msg "Warning: Unable to download Autounattend.xml" }
finally { $ProgressPreference = 'Continue' }
}
# Mount ISO Dialog
function Select-ISOFile {
Add-Type -AssemblyName System.Windows.Forms
$dialog = New-Object System.Windows.Forms.OpenFileDialog
$dialog.InitialDirectory = [Environment]::GetFolderPath("Desktop")
$dialog.Filter = "ISO files (*.iso)|*.iso"
$dialog.Title = "Select Windows ISO File"
if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
return $dialog.FileName
} else {
return $null
}
}
if ($isoPath) {$isoFilePath = $isoPath} # If ISO path is provided as parameter
else {$isoFilePath = Select-ISOFile} # Prompt user to select ISO file
if ($null -eq $isoFilePath) {
Write-Host "No file selected. Exiting Script" -ForegroundColor Red
Write-Log -msg "No file selected"
Pause
Exit
}
Write-Host "`nSelected ISO file: " -NoNewline -ForegroundColor Cyan; Write-Host "$isoFilePath"
Write-Log -msg "ISO Path: $isoFilePath"
# Mounting ISO File
$mountResult = Mount-DiskImage -ImagePath "$isoFilePath" -PassThru
if ($mountResult) {
$sourceDriveLetter = ($mountResult | Get-Volume).DriveLetter
if ($sourceDriveLetter) {
Write-Log -msg "Mounted ISO file to drive: $sourceDriveLetter`:"
}
}
else {
Write-Host "Failed to mount the ISO file." -ForegroundColor Red
Write-Log -msg "Failed to mount the ISO file."
Pause
Exit
}
$sourceDrive = "${sourceDriveLetter}:\" # Source Drive of ISO
$destinationPath = "$env:SystemDrive\WIDTemp\winlite" # Destination Path
$installMountDir = "$env:SystemDrive\WIDTemp\mountdir\installWIM" # Mount Directory
# Copy Files
Write-Host "`nCopying files from " -NoNewline; Write-Host "`"$sourceDrive`"" -ForegroundColor Yellow -NoNewline; Write-Host " to " -NoNewline; Write-Host "`"$destinationPath`"" -ForegroundColor Yellow; Write-Log -msg "Copying files from $sourceDrive to $destinationPath"
try {
if (-not (Test-Path $destinationPath)) { New-Item -ItemType Directory -Path $destinationPath -Force -EA Stop | Out-Null }
Write-Log -msg "Starting file copy operation..."
# Using Robocopy to copy files
$robocopyOutput = & robocopy.exe $sourceDrive $destinationPath /E /COPY:DAT /R:3 /W:5 /MT:8 /NFL /NDL /NP 2>&1
$robocopyExitCode = $LASTEXITCODE
$robocopyOutput | Write-Log
if ($robocopyExitCode -le 7) {
Write-Host "Copy completed successfully." -ForegroundColor Green
Write-Log -msg "Copy completed (Exit: $robocopyExitCode)"
Write-Log -msg "Removing read-only attributes..."
Get-ChildItem -Path $destinationPath -Recurse | ForEach-Object { $_.Attributes = $_.Attributes -band (-bnot [System.IO.FileAttributes]::ReadOnly) } | Out-Null
}
else { throw "Robocopy failed: $robocopyExitCode" }
} catch { Write-Log -msg "Copy failed: $($_.Exception.Message)"; throw }
try { Dismount-DiskImage -ImagePath $isoFilePath -EA Stop | Out-Null}
catch { Write-Log -msg "Dismount failed: $($_.Exception.Message)" }
# Check files availability
$installWimPath = Join-Path $destinationPath "sources\install.wim"
$installEsdPath = Join-Path $destinationPath "sources\install.esd"
New-Item -ItemType Directory -Path $installMountDir 2>&1 | Write-Log
# Handling install.wim and install.esd
if (-not (Test-Path $installWimPath)) {
Write-Host "`ninstall.wim not found. Searching for install.esd..."
if (Test-Path $installEsdPath) {
Write-Host "`ninstall.esd found at " -NoNewline -ForegroundColor Cyan; Write-Host "$installEsdPath"
Write-Log -msg "install.esd found. Converting..."
Write-Host "Details for image: " -NoNewline -ForegroundColor Cyan; Write-Host "$installEsdPath"
try {
# Get image info from install.esd
$esdInfo = Get-ImageIndex -ImagePath $installEsdPath
if (-not $esdInfo) {
Write-Host "Error: Could not retrieve image info from WIM file" -ForegroundColor Red
Remove-TempFiles
Pause
Exit
}
# Print image details from install.esd
foreach ($image in $esdInfo) {
Write-Host "$($image.Index). $($image.ImageName)"
}
# If winEdition is specified, find the index; else prompt user
if ($winEdition) {
$matchedImage = $esdInfo | Where-Object { $_.ImageName -ieq $winEdition }
if ($matchedImage) { $sourceIndex = $matchedImage.Index }
else { $sourceIndex = 1 }
}
else { $sourceIndex = Read-Host -Prompt "`nEnter the index to convert and mount" }
# Check if the index is valid, print selected "ImageIndex - ImageName"
$selectedImage = $esdInfo | Where-Object { $_.Index -eq [int]$sourceIndex }
if ($selectedImage) {
Write-Host "`nMounting image: " -NoNewline -ForegroundColor Cyan; Write-Host "$sourceIndex. $($selectedImage.ImageName)"
Write-Log -msg "Converting and Mounting image: $sourceIndex. $($selectedImage.ImageName)"
}
# Convert ESD to WIM
Invoke-DismFailsafe {Export-WindowsImage -SourceImagePath $installEsdPath -SourceIndex $sourceIndex -DestinationImagePath $installWimPath -CompressionType Maximum -CheckIntegrity} {dism /Export-Image /SourceImageFile:$installEsdPath /SourceIndex:$sourceIndex /DestinationImageFile:$installWimPath /Compress:max /CheckIntegrity}
# Remove the ESD file after conversion
Remove-Item $installEsdPath -Force
# Mount the converted WIM with SourceIndex 1
Invoke-DismFailsafe {Mount-WindowsImage -ImagePath $installWimPath -Index 1 -Path $installMountDir} {dism /mount-image /imagefile:$installWimPath /index:1 /mountdir:$installMountDir}
$sourceIndex = 1 # After conversion, the new WIM will have only one image
}
catch {
Write-Host "Failed to convert or mount the ESD image: $_" -ForegroundColor Red
Write-Log -msg "Failed to mount image: $_"
Pause
Exit
}
}
else {
Write-Host "Neither install.wim nor install.esd found. Make sure to mount the correct ISO" -ForegroundColor Red
Write-Log -msg "Neither install.wim nor install.esd found"
Pause
Exit
}
}
else {
Write-Host "`nDetails for image: " -NoNewline -ForegroundColor Cyan; Write-Host "$installWimPath"
Write-Log -msg "Getting image info"
try {
# Get image info from install.wim
$wimInfo = Get-ImageIndex -ImagePath $installWimPath
if (-not $wimInfo) {
Write-Host "Error: Could not retrieve image info from WIM file" -ForegroundColor Red
Remove-TempFiles
Pause
Exit
}
# Print image details from install.wim
foreach ($image in $wimInfo) {
Write-Host "$($image.Index). $($image.ImageName)"
}
# If winEdition is specified, find the index; else prompt user
if ($winEdition) {
$matchedImage = $wimInfo | Where-Object { $_.ImageName -ieq $winEdition }
if ($matchedImage) { $sourceIndex = $matchedImage.Index }
else { $sourceIndex = 1 }
}
else { $sourceIndex = Read-Host -Prompt "`nEnter the index to mount" }
# Check if the index is valid, print selected "ImageIndex - ImageName"
$selectedImage = $wimInfo | Where-Object { $_.Index -eq [int]$sourceIndex }
if ($selectedImage) {
Write-Host "`nMounting image: " -NoNewline -ForegroundColor Cyan; Write-Host "$sourceIndex. $($selectedImage.ImageName)"
Write-Log -msg "Mounting image: $sourceIndex. $($selectedImage.ImageName)"
}
Invoke-DismFailsafe {Mount-WindowsImage -ImagePath $installWimPath -Index $sourceIndex -Path $installMountDir} {dism /mount-image /imagefile:$installWimPath /index:$sourceIndex /mountdir:$installMountDir}
}
catch {
Write-Host "Failed to mount the image: $_" -ForegroundColor Red
Write-Log -msg "Failed to mount image: $_"
Pause
Exit
}
}
# Check if wim-mount was successful
if (-not (Test-Path "$installMountDir\Windows")) {
Write-Host "Error while mounting image. Try again." -ForegroundColor Red
Write-Log -msg "Mounted image not found. Exiting"
Remove-TempFiles
Pause
Exit
}
# Resolve Image Info
$WimDetails = Get-WimDetails -MountPath $installMountDir
if (-not $WimDetails -or -not $WimDetails.BuildNumber -or -not $WimDetails.Language) {
Write-Host "Error: Could not retrieve WIM information from mounted path" -ForegroundColor Red
Remove-TempFiles
Pause
Exit
}
$langCode = $WimDetails.Language; Write-Log -msg "Detected Language: $langCode"
$buildNumber = $WimDetails.BuildNumber; Write-Log -msg "Detected Build Number: $buildNumber"
Write-Host
$DoAppxRemove = Get-ParameterValue -ParameterValue $AppxRemove -DefaultValue $true -Question "Remove unnecessary packages?" -Description "Recommended: Removes bloatware apps"
$DoCapabilitiesRemove = Get-ParameterValue -ParameterValue $CapabilitiesRemove -DefaultValue $true -Question "Remove unnecessary features?" -Description "Recommended: Removes optional Windows features"
$DoOnedriveRemove = Get-ParameterValue -ParameterValue $OnedriveRemove -DefaultValue $true -Question "Remove OneDrive?" -Description "Optional: Completely removes OneDrive"
$DoEDGERemove = Get-ParameterValue -ParameterValue $EDGERemove -DefaultValue $true -Question "Remove Microsoft Edge?" -Description "Optional: Removes Edge components (Breaks Widgets)"
$DoAIRemove = Get-ParameterValue -ParameterValue $AIRemove -DefaultValue $true -Question "Remove AI Components?" -Description "Optional: Removes everything related to AI"
$DoTPMBypass = Get-ParameterValue -ParameterValue $TPMBypass -DefaultValue $false -Question "Bypass TPM check?" -Description "Only if needed for older hardware"
$DoUserFoldersEnable = Get-ParameterValue -ParameterValue $UserFoldersEnable -DefaultValue $true -Question "Enable user folders?" -Description "Recommended: Enables Desktop, Documents, etc."
$DoDriverIntegrate = Get-ParameterValue -ParameterValue $DriverIntegrate -DefaultValue $false -Question "Integrate Intel RST/VMD drivers?" -Description "Optional: Helps with Intel VMD storage controllers"
$DoESDConvert = Get-ParameterValue -ParameterValue $ESDConvert -DefaultValue $false -Question "Compress the ISO?" -Description "Recommended but slow: Reduces ISO file size"
$DoUseOscdimg = Get-ParameterValue -ParameterValue $useOscdimg -DefaultValue $true -Question "Use Oscdimg for ISO creation?" -Description "Recommended: Oscdimg is more reliable"
# Comment out the package don't wanna remove
$appxPatternsToRemove = @(
"Microsoft.Microsoft3DViewer*", # 3DViewer
"Microsoft.WindowsAlarms*", # Alarms
"Microsoft.BingNews*", # Bing News
"Microsoft.BingSearch*", # Bing Search
"Microsoft.BingWeather*", # Bing Weather (Removing Breaks Widgets)
"Windows.CBSPreview*", # CBS Preview
"Clipchamp.Clipchamp*", # Clipchamp
"Microsoft.549981C3F5F10*", # Cortana
"MicrosoftWindows.CrossDevice*", # CrossDevice
"Microsoft.Windows.DevHome*", # DevHome
"MicrosoftCorporationII.MicrosoftFamily*", # Family
"Microsoft.WindowsFeedbackHub*", # FeedbackHub
"Microsoft.GetHelp*", # GetHelp
"Microsoft.Getstarted*", # GetStarted
"Microsoft.WindowsCommunicationsapps*", # Mail
"Microsoft.WindowsMaps*", # Maps
"Microsoft.MixedReality.Portal*", # MixedReality
"Microsoft.ZuneMusic*", # Music
"Microsoft.MicrosoftOfficeHub*", # OfficeHub
"Microsoft.Office.OneNote*", # OneNote
"Microsoft.OutlookForWindows*", # Outlook
"Microsoft.MSPaint*", # Paint3D(Windows10)
"Microsoft.People*", # People
"Microsoft.Windows.PeopleExperienceHost*", # PeopleExperienceHost
"Microsoft.YourPhone*", # Phone
"Microsoft.PowerAutomateDesktop*", # PowerAutomate
"MicrosoftCorporationII.QuickAssist*", # QuickAssist
"Microsoft.SkypeApp*", # Skype
"Microsoft.MicrosoftStickyNotes*", # Sticky Notes
"Microsoft.MicrosoftSolitaireCollection*", # SolitaireCollection
# "Microsoft.WindowsSoundRecorder*", # SoundRecorder
"MicrosoftTeams*", # Teams_old
"MSTeams*", # Teams
"Microsoft.Windows.Teams*", # Teams
"Microsoft.Todos*", # Todos
"Microsoft.ZuneVideo*", # Video
"Microsoft.Wallet*", # Wallet
"Microsoft.GamingApp*", # Xbox
"Microsoft.XboxApp*", # Xbox(Win10)
"Microsoft.XboxGameOverlay*", # XboxGameOverlay
"Microsoft.XboxGamingOverlay*", # XboxGamingOverlay
# "Microsoft.XboxIdentityProvider*", # Xbox Identity Provider (Removing Breaks some Xbox Games)
"Microsoft.XboxSpeechToTextOverlay*", # XboxSpeechToTextOverlay
"Microsoft.Xbox.TCUI*" # XboxTitleCallableUI
# "Microsoft.SecHealthUI*" # Windows Security (Caution)
)
$capabilitiesToRemove = @(
"Browser.InternetExplorer*",
"Internet-Explorer*",
"App.StepsRecorder*",
"Language.Handwriting~~~$langCode*",
"Language.OCR~~~$langCode*",
"Language.Speech~~~$langCode*",
"Language.TextToSpeech~~~$langCode*",
"Microsoft.Windows.WordPad*",
"MathRecognizer*",
"Microsoft.Windows.PowerShell.ISE*",
# "Hello.Face*", # Removing Breaks Windows-Hello
"Media.WindowsMediaPlayer*"
)
$windowsPackagesToRemove = @(
"Microsoft-Windows-InternetExplorer-Optional-Package*",
"Microsoft-Windows-LanguageFeatures-Handwriting-$langCode-Package*",
"Microsoft-Windows-LanguageFeatures-OCR-$langCode-Package*",
"Microsoft-Windows-LanguageFeatures-Speech-$langCode-Package*",
"Microsoft-Windows-LanguageFeatures-TextToSpeech-$langCode-Package*",
"Microsoft-Windows-Wallpaper-Content-Extended-FoD-Package*",
"Microsoft-Windows-WordPad-FoD-Package*",
"Microsoft-Windows-MediaPlayer-Package*",
"Microsoft-Windows-TabletPCMath-Package*",
# "Microsoft-Windows-Hello-Face-Package", # Removing Breaks Windows-Hello
"Microsoft-Windows-StepsRecorder-Package*"
)
function Remove-Packages {
param( [string[]]$Patterns, [string]$SectionTitle, [string]$PackageType, [string]$MountPath, [int]$StartIndex = 1, [int]$TotalCount, [int]$StatusColumn )
# Package configurations
$config = @{
'AppX' = @{
GetCommand = { Get-ProvisionedAppxPackage -Path $MountPath }
FilterProperty = 'PackageName'
RemoveCommand = { param($item) Remove-ProvisionedAppxPackage -Path $MountPath -PackageName $item.PackageName }
LogPrefix = 'AppX package'
}
'Capability' = @{
GetCommand = { Get-WindowsCapability -Path $MountPath }
FilterProperty = 'Name'
RemoveCommand = { param($item) Remove-WindowsCapability -Path $MountPath -Name $item.Name }
LogPrefix = 'capability'
}
'WindowsPackage' = @{
GetCommand = { Get-WindowsPackage -Path $MountPath }
FilterProperty = 'PackageName'
RemoveCommand = { param($item) Remove-WindowsPackage -Path $MountPath -PackageName $item.PackageName }
LogPrefix = 'Windows package'
}
}
if ($SectionTitle) { Write-Host "`n$SectionTitle" -ForegroundColor Cyan; Write-Log -msg $SectionTitle }
# Validate Package Type
$cfg = $config[$PackageType]
$filterProp = $cfg.FilterProperty
for ($i = 0; $i -lt $Patterns.Count; $i++) {
$pattern = $Patterns[$i]
$displayName = $pattern.TrimEnd('*')
$counter = "[{0}/{1}]" -f ($StartIndex + $i), $TotalCount
$initialOutput = " $counter $displayName"
Write-Host $initialOutput -NoNewline # Display initial output
try {
$items = & $cfg.GetCommand | Where-Object { $_.$filterProp -like $pattern }
$itemsRemoved = 0
foreach ($item in $items) {
try {
& $cfg.RemoveCommand $item 2>&1 | Write-Log
$itemsRemoved++
}
catch {
$itemName = $item.$filterProp
Write-Log -msg "Removing $($cfg.LogPrefix) $itemName failed: $_"
}
}
# Show status
$padding = $StatusColumn - $initialOutput.Length
$spaces = ' ' * $padding
if ($itemsRemoved -gt 0) { Write-Host "$spaces[REMOVED]" -ForegroundColor Green }
else { Write-Host "$spaces[NOT FOUND]" -ForegroundColor Yellow }
}
catch {
Write-Log -msg "Failed to remove $PackageType matching '$pattern': $_"
$padding = $StatusColumn - $initialOutput.Length
Write-Host "$(' ' * $padding)[ERROR]" -ForegroundColor Red
}
}
}
$allPatterns = $appxPatternsToRemove + $capabilitiesToRemove + $windowsPackagesToRemove
$maxLength = ($allPatterns | ForEach-Object { $_.TrimEnd('*').Length } | Measure-Object -Maximum).Maximum
$statusColumn = $maxLength + 18
# Remove AppX Packages
if ($DoAppxRemove) {
Remove-Packages -Patterns $appxPatternsToRemove -SectionTitle "Removing provisioned Packages:" -PackageType "AppX" -MountPath $installMountDir -TotalCount $appxPatternsToRemove.Count -StatusColumn $statusColumn
} else {
Write-Log -msg "Skipped Package Removal"
}
# Remove Capabilities and Windows Packages
if ($DoCapabilitiesRemove) {
$capabilitiesAndPackagesTotal = $capabilitiesToRemove.Count + $windowsPackagesToRemove.Count
Remove-Packages -Patterns $capabilitiesToRemove -SectionTitle "Removing Unnecessary Windows Features:" -PackageType "Capability" -MountPath $installMountDir -TotalCount $capabilitiesAndPackagesTotal -StatusColumn $statusColumn
Remove-Packages -Patterns $windowsPackagesToRemove -SectionTitle "" -PackageType "WindowsPackage" -MountPath $installMountDir -StartIndex ($capabilitiesToRemove.Count + 1) -TotalCount $capabilitiesAndPackagesTotal -StatusColumn $statusColumn
} else {
Write-Log -msg "Skipped Features Removal"
}
# # Remove Recall (Have conflict with Explorer)
# Write-Host "`nRemoving Recall..."
# Write-Log -msg "Removing Recall"
# dism /image:$installMountDir /Disable-Feature /FeatureName:'Recall' /Remove 2>&1 | Write-Log
# Write-Host "Done"
# # Remove OutlookPWA
# Write-Host "`nRemoving Outlook..." -ForegroundColor Cyan
# Write-Log -msg "Removing OutlookPWA"
# Get-ChildItem "$installMountDir\Windows\WinSxS\amd64_microsoft-windows-outlookpwa*" -Directory | ForEach-Object { Set-OwnAndRemove -Path $_.FullName } 2>&1 | Write-Log
# Write-Host "Done" -ForegroundColor Green
# Setting Permissions
function Enable-Privilege {
param([ValidateSet('SeAssignPrimaryTokenPrivilege', 'SeAuditPrivilege', 'SeBackupPrivilege', 'SeChangeNotifyPrivilege', 'SeCreateGlobalPrivilege', 'SeCreatePagefilePrivilege', 'SeCreatePermanentPrivilege', 'SeCreateSymbolicLinkPrivilege', 'SeCreateTokenPrivilege', 'SeDebugPrivilege', 'SeEnableDelegationPrivilege', 'SeImpersonatePrivilege', 'SeIncreaseBasePriorityPrivilege', 'SeIncreaseQuotaPrivilege', 'SeIncreaseWorkingSetPrivilege', 'SeLoadDriverPrivilege', 'SeLockMemoryPrivilege', 'SeMachineAccountPrivilege', 'SeManageVolumePrivilege', 'SeProfileSingleProcessPrivilege', 'SeRelabelPrivilege', 'SeRemoteShutdownPrivilege', 'SeRestorePrivilege', 'SeSecurityPrivilege', 'SeShutdownPrivilege', 'SeSyncAgentPrivilege', 'SeSystemEnvironmentPrivilege', 'SeSystemProfilePrivilege', 'SeSystemtimePrivilege', 'SeTakeOwnershipPrivilege', 'SeTcbPrivilege', 'SeTimeZonePrivilege', 'SeTrustedCredManAccessPrivilege', 'SeUndockPrivilege', 'SeUnsolicitedInputPrivilege')]$Privilege, $ProcessId = $pid, [Switch]$Disable)
$def = @'
using System;using System.Runtime.InteropServices;public class AdjPriv{[DllImport("advapi32.dll",ExactSpelling=true,SetLastError=true)]internal static extern bool AdjustTokenPrivileges(IntPtr htok,bool disall,ref TokPriv1Luid newst,int len,IntPtr prev,IntPtr relen);[DllImport("advapi32.dll",ExactSpelling=true,SetLastError=true)]internal static extern bool OpenProcessToken(IntPtr h,int acc,ref IntPtr phtok);[DllImport("advapi32.dll",SetLastError=true)]internal static extern bool LookupPrivilegeValue(string host,string name,ref long pluid);[StructLayout(LayoutKind.Sequential,Pack=1)]internal struct TokPriv1Luid{public int Count;public long Luid;public int Attr;}public static bool EnablePrivilege(long processHandle,string privilege,bool disable){var tp=new TokPriv1Luid();tp.Count=1;tp.Attr=disable?0:2;IntPtr htok=IntPtr.Zero;if(!OpenProcessToken(new IntPtr(processHandle),0x28,ref htok))return false;if(!LookupPrivilegeValue(null,privilege,ref tp.Luid))return false;return AdjustTokenPrivileges(htok,false,ref tp,0,IntPtr.Zero,IntPtr.Zero);}}
'@
(Add-Type $def -PassThru -EA SilentlyContinue)[0]::EnablePrivilege((Get-Process -id $ProcessId).Handle, $Privilege, $Disable)
}
Enable-Privilege SeTakeOwnershipPrivilege | Out-Null
# Remove OneDrive
if ($DoOnedriveRemove) {
Write-Host ("`n[INFO] Removing OneDrive...") -ForegroundColor Cyan
Write-Log -msg "Defining OneDrive Setup file paths"
$oneDriveSetupPath1 = Join-Path -Path $installMountDir -ChildPath 'Windows\System32\OneDriveSetup.exe'
$oneDriveSetupPath2 = Join-Path -Path $installMountDir -ChildPath 'Windows\SysWOW64\OneDriveSetup.exe'
# $oneDriveSetupPath3 = (Join-Path -Path $installMountDir -ChildPath 'Windows\WinSxS\*microsoft-windows-onedrive-setup*\OneDriveSetup.exe' | Get-Item -ErrorAction SilentlyContinue).FullName
# $oneDriveSetupPath4 = (Get-ChildItem "$installMountDir\Windows\WinSxS\amd64_microsoft-windows-onedrive-setup*" -Directory).FullName
$oneDriveShortcut = Join-Path -Path $installMountDir -ChildPath 'Users\Default\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\OneDrive.lnk'
Write-Log -msg "Removing OneDrive"
Set-OwnAndRemove -Path $oneDriveSetupPath1 | Out-Null
Set-OwnAndRemove -Path $oneDriveSetupPath2 | Out-Null
# $oneDriveSetupPath3 | Where-Object { $_ } | ForEach-Object { Set-OwnAndRemove -Path $_ } 2>&1 | Write-Log
# $oneDriveSetupPath4 | Where-Object { $_ } | ForEach-Object { Set-OwnAndRemove -Path $_ } 2>&1 | Write-Log
Set-OwnAndRemove -Path $oneDriveShortcut | Out-Null
Write-Host ("[OK] OneDrive Removed") -ForegroundColor Green
Write-Log -msg "OneDrive removed successfully"
} else {
Write-Log -msg "OneDrive removal skipped"
}
# Remove EDGE
if ($DoEDGERemove) {
Write-Host ("`n[INFO] Removing EDGE...") -ForegroundColor Cyan
Write-Log -msg "Removing EDGE"
# Remove Edge using DISM
Write-Log -msg "Executing DISM - Remove-Edge"
dism /image:"$installMountDir" /Remove-Edge 2>&1 | Write-Log
# Edge Patterns
$EDGEpatterns = @(
"Microsoft.MicrosoftEdge.Stable*",
"Microsoft.MicrosoftEdgeDevToolsClient*",
"Microsoft.Win32WebViewHost*",
"MicrosoftWindows.Client.WebExperience*" # Removing Breaks Widgets
)
# Remove Edge Packages
foreach ($pattern in $EDGEpatterns) {
$matchedPackages = Get-ProvisionedAppxPackage -Path $installMountDir |
Where-Object { $_.PackageName -like $pattern }
foreach ($package in $matchedPackages) {
Invoke-DismFailsafe {Remove-ProvisionedAppxPackage -Path $installMountDir -PackageName $package.PackageName} {dism /image:$installMountDir /Remove-ProvisionedAppxPackage /PackageName:$($package.PackageName)}
}
}
# Remove WebView2 if not already removed
Get-WindowsCapability -Path $installMountDir | Where-Object { $_.Name -like "Edge.Webview2.Platform*" } |
ForEach-Object { Invoke-DismFailsafe {Remove-WindowsCapability -Path $installMountDir -Name $_.Name} {dism /image:$installMountDir /Remove-Capability /CapabilityName:$($_.Name)} }
Get-WindowsPackage -Path $installMountDir | Where-Object { $_.PackageName -like "Microsoft-Edge-WebView-FOD-Package*" } |
ForEach-Object { Invoke-DismFailsafe {Remove-WindowsPackage -Path $installMountDir -PackageName $_.PackageName} {dism /image:$installMountDir /Remove-Package /PackageName:$($_.PackageName)} }
# Modifying reg keys
try {
reg load HKLM\zSOFTWARE "$installMountDir\Windows\System32\config\SOFTWARE" 2>&1 | Write-Log
reg load HKLM\zSYSTEM "$installMountDir\Windows\System32\config\SYSTEM" 2>&1 | Write-Log
reg load HKLM\zNTUSER "$installMountDir\Users\Default\ntuser.dat" 2>&1 | Write-Log
reg load HKLM\zDEFAULT "$installMountDir\Windows\System32\config\default" 2>&1 | Write-Log
# Registry operations
reg delete "HKLM\zSOFTWARE\Microsoft\EdgeUpdate" /f 2>&1 | Write-Log
reg delete "HKLM\zSOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft Edge" /f 2>&1 | Write-Log
reg delete "HKLM\zDEFAULT\Software\Microsoft\EdgeUpdate" /f 2>&1 | Write-Log
reg delete "HKLM\zNTUSER\Software\Microsoft\EdgeUpdate" /f 2>&1 | Write-Log
reg delete "HKLM\zSOFTWARE\Microsoft\Active Setup\Installed Components\{9459C573-B17A-45AE-9F64-1857B5D58CEE}" /f 2>&1 | Write-Log
reg delete "HKLM\zSOFTWARE\WOW6432Node\Microsoft\Edge" /f 2>&1 | Write-Log
reg delete "HKLM\zSOFTWARE\WOW6432Node\Microsoft\EdgeUpdate" /f 2>&1 | Write-Log
reg delete "HKLM\zSYSTEM\CurrentControlSet\Services\edgeupdate" /f 2>&1 | Write-Log
reg delete "HKLM\zSYSTEM\ControlSet001\Services\edgeupdate" /f 2>&1 | Write-Log
reg delete "HKLM\zSYSTEM\CurrentControlSet\Services\edgeupdatem" /f 2>&1 | Write-Log
reg delete "HKLM\zSYSTEM\ControlSet001\Services\edgeupdatem" /f 2>&1 | Write-Log
reg delete "HKLM\zSOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft Edge" /f 2>&1 | Write-Log
reg delete "HKLM\zSOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft Edge Update" /f 2>&1 | Write-Log
reg add "HKLM\zSOFTWARE\Microsoft\MicrosoftEdge\Main" /v "AllowPrelaunch" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
reg add "HKLM\zSOFTWARE\Policies\Microsoft\MicrosoftEdge\Main" /v "AllowPrelaunch" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
reg add "HKLM\zNTUSER\Software\Microsoft\MicrosoftEdge\Main" /v "AllowPrelaunch" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
reg add "HKLM\zNTUSER\Software\Policies\Microsoft\MicrosoftEdge\Main" /v "AllowPrelaunch" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
reg add "HKLM\zSOFTWARE\Microsoft\MicrosoftEdge\TabPreloader" /v "AllowTabPreloading" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
reg add "HKLM\zSOFTWARE\Policies\Microsoft\MicrosoftEdge\TabPreloader" /v "AllowTabPreloading" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
reg add "HKLM\zNTUSER\Software\Microsoft\MicrosoftEdge\TabPreloader" /v "AllowTabPreloading" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
reg add "HKLM\zNTUSER\Software\Policies\Microsoft\MicrosoftEdge\TabPreloader" /v "AllowTabPreloading" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
reg add "HKLM\zSOFTWARE\Policies\Microsoft\EdgeUpdate" /v "UpdateDefault" /t REG_DWORD /d "0" /f 2>&1 | Write-Log
# Disable Edge updates and installation
$registryKeys = @(
"HKLM\zSOFTWARE\Microsoft\EdgeUpdate",
"HKLM\zSOFTWARE\Policies\Microsoft\EdgeUpdate",
"HKLM\zSOFTWARE\WOW6432Node\Microsoft\EdgeUpdate",
"HKLM\zNTUSER\Software\Microsoft\EdgeUpdate",
"HKLM\zNTUSER\Software\Policies\Microsoft\EdgeUpdate"
)
foreach ($key in $registryKeys) {
reg add "$key" /v "DoNotUpdateToEdgeWithChromium" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
reg add "$key" /v "UpdaterExperimentationAndConfigurationServiceControl" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
reg add "$key" /v "InstallDefault" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
}
}
catch {
Write-Log -msg "Error modifying registry: $_"
}
finally {
# Always unload registry hives regardless of errors
reg unload HKLM\zSOFTWARE 2>&1 | Write-Log
reg unload HKLM\zSYSTEM 2>&1 | Write-Log
reg unload HKLM\zNTUSER 2>&1 | Write-Log
reg unload HKLM\zDEFAULT 2>&1 | Write-Log
}
# Remove EDGE files
Remove-Item -Path "$installMountDir\Program Files\Microsoft\Edge" -Recurse -Force 2>&1 | Write-Log
Remove-Item -Path "$installMountDir\Program Files\Microsoft\EdgeCore" -Recurse -Force 2>&1 | Write-Log
Remove-Item -Path "$installMountDir\Program Files\Microsoft\EdgeUpdate" -Recurse -Force 2>&1 | Write-Log
Remove-Item -Path "$installMountDir\Program Files\Microsoft\EdgeWebView" -Recurse -Force 2>&1 | Write-Log
Remove-Item -Path "$installMountDir\Program Files (x86)\Microsoft\Edge" -Recurse -Force 2>&1 | Write-Log
Remove-Item -Path "$installMountDir\Program Files (x86)\Microsoft\EdgeCore" -Recurse -Force 2>&1 | Write-Log
Remove-Item -Path "$installMountDir\Program Files (x86)\Microsoft\EdgeUpdate" -Recurse -Force 2>&1 | Write-Log
Remove-Item -Path "$installMountDir\Program Files (x86)\Microsoft\EdgeWebView" -Recurse -Force 2>&1 | Write-Log
Remove-Item -Path "$installMountDir\ProgramData\Microsoft\EdgeUpdate" -Recurse -Force 2>&1 | Write-Log
Get-ChildItem "$installMountDir\ProgramData\Microsoft\Windows\AppRepository\Packages\Microsoft.MicrosoftEdge.Stable*" -Directory | ForEach-Object { Set-OwnAndRemove -Path $_.FullName } 2>&1 | Write-Log
Get-ChildItem "$installMountDir\ProgramData\Microsoft\Windows\AppRepository\Packages\Microsoft.MicrosoftEdgeDevToolsClient*" -Directory | ForEach-Object { Set-OwnAndRemove -Path $_.FullName } 2>&1 | Write-Log
# Get-ChildItem "$installMountDir\Windows\WinSxS\*microsoft-edge-webview*" -Directory | ForEach-Object { Set-OwnAndRemove -Path $_.FullName } 2>&1 | Write-Log
Set-OwnAndRemove -Path (Join-Path -Path $installMountDir -ChildPath 'Windows\System32\Microsoft-Edge-WebView') | Out-Null
Get-Item (Join-Path -Path $installMountDir -ChildPath 'Windows\SystemApps\Microsoft.Win32WebViewHost*') -ErrorAction SilentlyContinue | ForEach-Object { Set-OwnAndRemove -Path $_.FullName | Out-Null }
# Removing EDGE-Task
Get-ChildItem -Path "$installMountDir\Windows\System32\Tasks\MicrosoftEdge*" | Where-Object { $_ } | ForEach-Object { Set-OwnAndRemove -Path $_ } 2>&1 | Write-Log
# For Windows 10 (Legacy EDGE)
if ($buildNumber -lt 22000) {
Get-ChildItem -Path "$installMountDir\Windows\SystemApps\Microsoft.MicrosoftEdge*" | Where-Object { $_ } | ForEach-Object { Set-OwnAndRemove -Path $_ } 2>&1 | Write-Log
}
Write-Host ("[OK] EDGE has been removed") -ForegroundColor Green
Write-Log -msg "Microsoft Edge removal completed"
} else {
Write-Log -msg "Edge removal cancelled"
}
# Remove AI components
if ($buildNumber -ge 22000) {
if ($DoAIRemove) {
Write-Host ("`n[INFO] Removing AI components...") -ForegroundColor Cyan
Write-Log -msg "Removing AI components"
# Remove AI Packages
$AIpatterns = @(
"Microsoft.Windows.Copilot*",
"Microsoft.Copilot*"
)
foreach ($pattern in $AIpatterns) {
$matchedPackages = Get-ProvisionedAppxPackage -Path $installMountDir |
Where-Object { $_.PackageName -like $pattern }
foreach ($package in $matchedPackages) {
Invoke-DismFailsafe {Remove-ProvisionedAppxPackage -Path $installMountDir -PackageName $package.PackageName} {dism /image:$installMountDir /Remove-ProvisionedAppxPackage /PackageName:$($package.PackageName)}
}
}
# Disable AI DLLs
$dllfiles = @('System32', 'SysWOW64') | ForEach-Object {
Join-Path $installMountDir "Windows\$_\Windows.AI.MachineLearning.dll"
Join-Path $installMountDir "Windows\$_\Windows.AI.MachineLearning.Preview.dll"
}
$dllfiles += Join-Path $installMountDir "Windows\System32\SettingsHandlers_Copilot.dll"
$dllfiles | Where-Object { Test-Path $_ } | ForEach-Object {
Set-Ownership -Path $_ | Out-Null
try { Rename-Item $_ ($_ + ".bak") -Force -ErrorAction Stop 2>&1 | Write-Log }
catch {
Write-Log -msg "Rename failed for $_. Attempting to delete..."
Set-OwnAndRemove -Path $_ 2>&1 | Write-Log
}
}
# Modifying reg keys
try {
reg load HKLM\zSOFTWARE "$installMountDir\Windows\System32\config\SOFTWARE" 2>&1 | Write-Log
reg load HKLM\zSYSTEM "$installMountDir\Windows\System32\config\SYSTEM" 2>&1 | Write-Log
reg load HKLM\zNTUSER "$installMountDir\Users\Default\ntuser.dat" 2>&1 | Write-Log
# Registry operations
reg add "HKLM\zSOFTWARE\Policies\Microsoft\Windows\Explorer" /v "DisableSearchBoxSuggestions" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
# Disable AI in Notepad
reg add "HKLM\zSOFTWARE\Policies\WindowsNotepad" /v "DisableAIFeatures" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
# Disable AI in Paint
reg add "HKLM\zSOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Paint" /v "DisableCocreator" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
reg add "HKLM\zSOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Paint" /v "DisableImageCreator" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
# Disable AI in other apps
reg add "HKLM\zSOFTWARE\Policies\Microsoft\Windows\AppPrivacy" /v "LetAppsAccessSystemAIModels" /t REG_DWORD /d "2" /f 2>&1 | Write-Log
reg add "HKLM\zSOFTWARE\Policies\Microsoft\Windows\AppPrivacy" /v "LetAppsAccessGenerativeAI" /t REG_DWORD /d "2" /f 2>&1 | Write-Log
# Disable AI access
reg add "HKLM\zSOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\generativeAI" /v "Value" /t REG_SZ /d "Deny" /f 2>&1 | Write-Log
# Disable AI in Edge
reg add "HKLM\zSOFTWARE\Policies\Microsoft\Edge" /v "HubsSidebarEnabled" /t REG_DWORD /d "0" /f 2>&1 | Write-Log
reg add "HKLM\zSOFTWARE\Policies\Microsoft\Edge" /v "CopilotPageContext" /t REG_DWORD /d "0" /f 2>&1 | Write-Log
reg add "HKLM\zSOFTWARE\Policies\Microsoft\Edge" /v "CopilotCDPPageContext" /t REG_DWORD /d "0" /f 2>&1 | Write-Log
# Disable AI in Search
reg add "HKLM\zSOFTWARE\Policies\Microsoft\Windows\WindowsAI" /v "DisableClickToDo" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
# Disable WSAIFabricSvc Service on first logon
reg add "HKLM\zSOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce" /v "DisableWSAIFabricSvc" /t REG_SZ /d 'reg add "HKLM\SYSTEM\CurrentControlSet\Services\WSAIFabricSvc" /v "Start" /t REG_DWORD /d "4" /f'
reg add "HKLM\zSOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce" /v "StopWSAIFabricSvc" /t REG_SZ /d "net stop WSAIFabricSvc"
# Hide AI components from Settings
reg add "HKLM\zSOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer" /v "SettingsPageVisibility" /t REG_SZ /d "hide:aicomponents" /f 2>&1 | Write-Log
# Disable AI from Explorer
reg add "HKLM\zNTUSER\Software\Microsoft\Windows\CurrentVersion\WindowsCopilot" /v "AllowCopilotRuntime" /t REG_DWORD /d "0" /f 2>&1 | Write-Log
reg add "HKLM\zNTUSER\Software\Microsoft\Windows\CurrentVersion\Explorer\Taskband\AuxilliaryPins" /v "CopilotPWAPin" /t REG_DWORD /d "0" /f 2>&1 | Write-Log
reg add "HKLM\zNTUSER\Software\Microsoft\Windows\CurrentVersion\Explorer\Taskband\AuxilliaryPins" /v "RecallPin" /t REG_DWORD /d "0" /f 2>&1 | Write-Log
# Disable Copilot and Recall system-wide
reg add "HKLM\zSOFTWARE\Policies\Microsoft\Windows\WindowsCopilot" /v "TurnOffWindowsCopilot" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
reg add "HKLM\zSOFTWARE\Policies\Microsoft\Windows\WindowsAI" /v "DisableAIDataAnalysis" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
reg add "HKLM\zSOFTWARE\Policies\Microsoft\Windows\WindowsAI" /v "AllowRecallEnablement" /t REG_DWORD /d "0" /f 2>&1 | Write-Log
reg add "HKLM\zSOFTWARE\Policies\Microsoft\Windows\WindowsAI" /v "TurnOffSavingSnapshots" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
reg add "HKLM\zSOFTWARE\Policies\Microsoft\Windows\WindowsAI" /v "DisableSettingsAgent" /t REG_DWORD /d "1" /f 2>&1 | Write-Log
reg add "HKLM\zSOFTWARE\Microsoft\Windows\Shell\Copilot" /v "IsCopilotAvailable" /t REG_DWORD /d "0" /f 2>&1 | Write-Log