-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeployWorkstation.ps1
More file actions
1358 lines (1190 loc) · 57.4 KB
/
DeployWorkstation.ps1
File metadata and controls
1358 lines (1190 loc) · 57.4 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
# DeployWorkstation.ps1 – Optimized Win10/11 Setup & Clean-up
# Version: 5.1 – PNWC Edition 4.1.2026
# New in 5.0: Write-Progress console bars, embedded en-US / es-ES localization
# New in 5.1: Winget auto-bootstrap, install retry logic, WU guard, OEM OneDrive, edition awareness
#Requires -Version 5.1
#Requires -RunAsAdministrator
[CmdletBinding()]
param(
[string]$LogPath,
[string]$ReportPath,
[switch]$SkipAppInstall,
[switch]$SkipBloatwareRemoval,
[switch]$SkipSystemConfig
)
# ================================
# Configuration & Setup
# ================================
$ErrorActionPreference = 'Continue'
$ProgressPreference = 'Continue' # Must be Continue for Write-Progress to render
$script:StartTime = Get-Date
# $PSScriptRoot is read-only in PS5.1 — use a separate variable for fallback safety
$scriptRoot = if ($PSScriptRoot) { $PSScriptRoot } else { Split-Path -Parent $MyInvocation.MyCommand.Path }
if (-not $LogPath) { $LogPath = Join-Path $scriptRoot 'DeployWorkstation.log' }
if (-not $ReportPath) { $ReportPath = Join-Path $scriptRoot 'DeployWorkstation.html' }
# --------------------------------
# Restart in Windows PowerShell 5.1 if running under PS Core
# --------------------------------
if ($PSVersionTable.PSEdition -eq 'Core') {
Write-Warning 'PowerShell Core detected. Restarting in Windows PowerShell 5.1...'
# Wrap path values in escaped quotes so spaces in paths survive Start-Process argument joining
$params = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', "`"$PSCommandPath`"",
'-LogPath', "`"$LogPath`"", '-ReportPath', "`"$ReportPath`"")
if ($SkipAppInstall) { $params += '-SkipAppInstall' }
if ($SkipBloatwareRemoval) { $params += '-SkipBloatwareRemoval' }
if ($SkipSystemConfig) { $params += '-SkipSystemConfig' }
Start-Process -FilePath 'powershell.exe' -ArgumentList $params -Verb RunAs
exit
}
# ================================
# Localization
# ================================
# Auto-detected from Get-Culture, falls back to en-US.
# To add a new language: copy the en-US block, change the key, translate the values.
# Progress bars, log messages, summary labels, and HTML report headings are all localized.
$script:Strings = @{
'en-US' = @{
# Startup
Started = 'DeployWorkstation v5.1 Started'
WingetRequired = "Winget is required. Install 'App Installer' from the Microsoft Store."
WingetFound = 'Winget found'
WingetMissing = 'Winget not found on PATH.'
ManagingSources = 'Managing winget sources'
ProgSources = 'Managing Winget Sources'
RemovingMsstore = 'Removing msstore source (performance)'
RefreshingSources = 'Refreshing winget source index'
SourcesFailed = 'Could not manage winget sources'
# Phase names (console + progress bar)
PhaseBloatware = 'BLOATWARE REMOVAL'
PhaseApps = 'APP INSTALLATION'
PhaseConfig = 'SYSTEM CONFIGURATION'
PhaseReporting = 'GENERATING REPORT'
# Skip messages
SkipBloatware = 'Bloatware removal skipped (-SkipBloatwareRemoval).'
SkipApps = 'App installation skipped (-SkipAppInstall).'
SkipConfig = 'System configuration skipped (-SkipSystemConfig).'
# Progress bar activity labels
ProgOverall = 'Deploying Workstation'
ProgBloatware = 'Removing Bloatware'
ProgAppx = 'Removing Appx Packages'
ProgCaps = 'Removing Windows Capabilities'
ProgMcAfee = 'Checking for McAfee'
ProgApps = 'Installing Applications'
ProgConfig = 'Configuring System'
# Item-level actions / outcomes
Checking = 'Checking'
NotFound = 'Not found'
Removing = 'Removing'
Removed = 'Removed'
RemoveExitCode = 'Removal exit code'
RemoveError = 'Error removing'
AppxRemoving = 'Removing Appx'
AppxProvRemoving = 'Removing provisioned'
NotInstalled = 'Not installed'
Installing = 'Installing'
InstallOK = 'OK'
AlreadyInstalled = 'Already installed'
InstallFail = 'Failed'
InstallError = 'Error installing'
CapRemoving = 'Removing capability'
CapError = 'Error with capability'
McAfeeNone = 'No McAfee products found.'
McAfeeFound = 'Found'
McAfeeNoStr = 'No uninstall string'
McAfeeUninstall = 'Uninstalling'
McAfeeRemoved = 'Removed'
McAfeeFailed = 'Failed to uninstall'
RegistryOK = 'Registry OK'
RegistryFail = 'Registry FAIL'
SysConfigDone = 'System configuration complete.'
# Summary labels
SumTitle = 'DEPLOYMENT SUMMARY'
SumAppsOK = 'Apps installed / skipped'
SumAppsFail = 'Apps failed'
SumAppx = 'Appx packages removed'
SumCaps = 'Capabilities removed'
SumConfigOK = 'Config keys applied'
SumConfigFail = 'Config keys failed'
SumMcAfee = 'McAfee products removed'
# Completion
Completed = 'DeployWorkstation.ps1 Completed'
SetupComplete = 'Setup complete!'
SetupFailed = 'Setup failed - see log'
PressEnter = 'Press Enter to exit...'
ReportSaved = 'HTML report saved'
ReportFail = 'Failed to write HTML report'
CriticalError = 'CRITICAL ERROR'
# Winget bootstrap
WingetOld = 'Winget outdated, updating'
WingetBootstrap = 'Installing App Installer (winget)'
WingetBootOK = 'App Installer installed successfully'
WingetBootFail = 'Failed to install App Installer'
WingetReRegister = 'Attempting package re-registration'
WingetDownload = 'Downloading App Installer from Microsoft'
# Reliability
InstallRetrying = 'Network error, retrying'
CapWuUnavail = 'Skipped - Windows Update not accessible on this system'
HomeEditionNote = 'Policy key written but has no effect on Windows Home edition'
OneDriveOem = 'OneDrive OEM binary removal'
OneDriveOemFound = 'Found OEM OneDrive binary'
OneDriveOemDone = 'OEM OneDrive uninstall completed'
OneDriveOemNone = 'No OEM OneDrive setup binary found'
# HTML report additions
HtmlEdition = 'Edition'
HtmlBuild = 'Build'
# Progress — winget init & report steps
ProgWingetCheck = 'Checking Winget'
ProgSourcesList = 'Listing sources'
ProgSourcesUpdate = 'Updating sources'
ProgReportCollect = 'Collecting system info'
ProgReportBuild = 'Building report'
ProgReportWrite = 'Writing report file'
# HTML report headings
HtmlTitle = 'DeployWorkstation Report'
HtmlGenerated = 'Generated'
HtmlSysInfo = 'System Information'
HtmlSummary = 'Summary'
HtmlResults = 'Detailed Results'
HtmlEventLog = 'Full Event Log (last 200 entries)'
HtmlHostname = 'Hostname'
HtmlOS = 'Operating System'
HtmlCPU = 'CPU'
HtmlRAM = 'RAM'
HtmlUptime = 'System Uptime'
HtmlRunTime = 'Script Run Time'
HtmlVersion = 'Script Version'
HtmlTechnician = 'Technician'
HtmlItem = 'Item'
HtmlStatus = 'Status'
HtmlDetail = 'Detail'
HtmlTimestamp = 'Timestamp'
HtmlLevel = 'Level'
HtmlMessage = 'Message'
HtmlAppsOK = 'Apps Installed / OK'
HtmlAppsFail = 'Apps Failed'
HtmlAppxRemoved = 'Appx Removed'
HtmlCapsRemoved = 'Capabilities Removed'
HtmlConfigOK = 'Config Keys Set'
HtmlConfigFail = 'Config Keys Failed'
HtmlMcAfee = 'McAfee Removed'
HtmlHrs = 'hrs'
}
'es-ES' = @{
# Startup
Started = 'DeployWorkstation v5.1 Iniciado'
WingetRequired = "Se requiere Winget. Instale 'App Installer' desde Microsoft Store."
WingetFound = 'Winget encontrado'
WingetMissing = 'Winget no encontrado en el PATH.'
ManagingSources = 'Administrando fuentes de winget'
ProgSources = 'Administrando Fuentes de Winget'
RemovingMsstore = 'Eliminando fuente msstore (rendimiento)'
RefreshingSources = 'Actualizando indice de fuentes winget'
SourcesFailed = 'No se pudieron administrar las fuentes de winget'
# Phase names
PhaseBloatware = 'ELIMINACION DE SOFTWARE NO DESEADO'
PhaseApps = 'INSTALACION DE APLICACIONES'
PhaseConfig = 'CONFIGURACION DEL SISTEMA'
PhaseReporting = 'GENERANDO INFORME'
# Skip messages
SkipBloatware = 'Eliminacion de software omitida (-SkipBloatwareRemoval).'
SkipApps = 'Instalacion de aplicaciones omitida (-SkipAppInstall).'
SkipConfig = 'Configuracion del sistema omitida (-SkipSystemConfig).'
# Progress bar activity labels
ProgOverall = 'Configurando Estacion de Trabajo'
ProgBloatware = 'Eliminando Software No Deseado'
ProgAppx = 'Eliminando Paquetes Appx'
ProgCaps = 'Eliminando Capacidades de Windows'
ProgMcAfee = 'Verificando McAfee'
ProgApps = 'Instalando Aplicaciones'
ProgConfig = 'Configurando Sistema'
# Item-level actions / outcomes
Checking = 'Verificando'
NotFound = 'No encontrado'
Removing = 'Eliminando'
Removed = 'Eliminado'
RemoveExitCode = 'Codigo de salida de eliminacion'
RemoveError = 'Error al eliminar'
AppxRemoving = 'Eliminando Appx'
AppxProvRemoving = 'Eliminando paquete aprovisionado'
NotInstalled = 'No instalado'
Installing = 'Instalando'
InstallOK = 'OK'
AlreadyInstalled = 'Ya instalado'
InstallFail = 'Fallo'
InstallError = 'Error al instalar'
CapRemoving = 'Eliminando capacidad'
CapError = 'Error con capacidad'
McAfeeNone = 'No se encontraron productos McAfee.'
McAfeeFound = 'Encontrado'
McAfeeNoStr = 'Sin cadena de desinstalacion'
McAfeeUninstall = 'Desinstalando'
McAfeeRemoved = 'Eliminado'
McAfeeFailed = 'Error al desinstalar'
RegistryOK = 'Registro OK'
RegistryFail = 'Fallo de registro'
SysConfigDone = 'Configuracion del sistema completada.'
# Summary labels
SumTitle = 'RESUMEN DE DESPLIEGUE'
SumAppsOK = 'Aplicaciones instaladas / omitidas'
SumAppsFail = 'Aplicaciones fallidas'
SumAppx = 'Paquetes Appx eliminados'
SumCaps = 'Capacidades eliminadas'
SumConfigOK = 'Claves de configuracion aplicadas'
SumConfigFail = 'Claves de configuracion fallidas'
SumMcAfee = 'Productos McAfee eliminados'
# Completion
Completed = 'DeployWorkstation.ps1 Completado'
SetupComplete = 'Configuracion completada!'
SetupFailed = 'Configuracion fallida - ver registro'
PressEnter = 'Presione Enter para salir...'
ReportSaved = 'Informe HTML guardado'
ReportFail = 'Error al escribir el informe HTML'
CriticalError = 'ERROR CRITICO'
# Winget bootstrap
WingetOld = 'Winget desactualizado, actualizando'
WingetBootstrap = 'Instalando App Installer (winget)'
WingetBootOK = 'App Installer instalado exitosamente'
WingetBootFail = 'Error al instalar App Installer'
WingetReRegister = 'Intentando re-registro del paquete'
WingetDownload = 'Descargando App Installer de Microsoft'
# Reliability
InstallRetrying = 'Error de red, reintentando'
CapWuUnavail = 'Omitido - Windows Update no accesible en este sistema'
HomeEditionNote = 'Clave de politica escrita pero sin efecto en Windows Home'
OneDriveOem = 'Eliminacion de OneDrive OEM'
OneDriveOemFound = 'Binario OEM de OneDrive encontrado'
OneDriveOemDone = 'Desinstalacion de OneDrive OEM completada'
OneDriveOemNone = 'No se encontro binario de configuracion de OneDrive OEM'
# HTML report additions
HtmlEdition = 'Edicion'
HtmlBuild = 'Version de Compilacion'
# Progress — winget init & report steps
ProgWingetCheck = 'Verificando Winget'
ProgSourcesList = 'Listando fuentes'
ProgSourcesUpdate = 'Actualizando fuentes'
ProgReportCollect = 'Recopilando informacion del sistema'
ProgReportBuild = 'Construyendo informe'
ProgReportWrite = 'Escribiendo archivo de informe'
# HTML report headings
HtmlTitle = 'Informe de DeployWorkstation'
HtmlGenerated = 'Generado'
HtmlSysInfo = 'Informacion del Sistema'
HtmlSummary = 'Resumen'
HtmlResults = 'Resultados Detallados'
HtmlEventLog = 'Registro de Eventos (ultimas 200 entradas)'
HtmlHostname = 'Nombre de Host'
HtmlOS = 'Sistema Operativo'
HtmlCPU = 'Procesador'
HtmlRAM = 'Memoria RAM'
HtmlUptime = 'Tiempo de Actividad'
HtmlRunTime = 'Tiempo de Ejecucion'
HtmlVersion = 'Version del Script'
HtmlTechnician = 'Tecnico'
HtmlItem = 'Elemento'
HtmlStatus = 'Estado'
HtmlDetail = 'Detalle'
HtmlTimestamp = 'Marca de Tiempo'
HtmlLevel = 'Nivel'
HtmlMessage = 'Mensaje'
HtmlAppsOK = 'Aplicaciones Instaladas / OK'
HtmlAppsFail = 'Aplicaciones Fallidas'
HtmlAppxRemoved = 'Appx Eliminados'
HtmlCapsRemoved = 'Capacidades Eliminadas'
HtmlConfigOK = 'Claves de Config. Aplicadas'
HtmlConfigFail = 'Claves de Config. Fallidas'
HtmlMcAfee = 'McAfee Eliminados'
HtmlHrs = 'hrs'
}
}
# Resolve active language — exact match first, then primary tag, then en-US fallback
$culture = (Get-Culture).Name # e.g. 'es-ES', 'en-US'
$primaryTag = $culture.Split('-')[0] # e.g. 'es', 'en'
$resolvedLang = if ($script:Strings.ContainsKey($culture)) {
$culture
} else {
$tagMatch = $script:Strings.Keys |
Where-Object { $_ -match "^$primaryTag-" } |
Select-Object -First 1
if ($tagMatch) { $tagMatch } else { 'en-US' }
}
$script:Lang = $script:Strings[$resolvedLang]
# T() — short translate helper used throughout the script
function T {
param([string]$Key)
if ($script:Lang.ContainsKey($Key)) { return $script:Lang[$Key] }
return $Key # fall back to the key name itself if missing
}
# ConvertTo-HtmlSafe — encodes special chars so exception messages / paths
# don't break the HTML report structure
function ConvertTo-HtmlSafe {
param([string]$Text)
if (-not $Text) { return '' }
$Text -replace '&','&' -replace '<','<' -replace '>','>' -replace '"','"'
}
# ================================
# Logging
# ================================
$logDir = Split-Path $LogPath -Parent
if ($logDir -and -not (Test-Path $logDir)) {
New-Item -Path $logDir -ItemType Directory -Force | Out-Null
}
$script:EventLog = [System.Collections.Generic.List[hashtable]]::new()
function Write-Log {
param(
[string]$Message,
[ValidateSet('INFO','WARN','ERROR','SUCCESS','SECTION')]
[string]$Level = 'INFO'
)
$timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
$logEntry = "[$timestamp] [$Level] $Message"
$color = switch ($Level) {
'WARN' { 'Yellow' }
'ERROR' { 'Red' }
'SUCCESS' { 'Green' }
'SECTION' { 'Cyan' }
default { 'Gray' }
}
Write-Host $logEntry -ForegroundColor $color
Add-Content -Path $LogPath -Value $logEntry -Encoding UTF8
$script:EventLog.Add(@{ Timestamp = $timestamp; Level = $Level; Message = $Message })
}
# ================================
# Progress Bar Helpers
# ================================
# Two-tier layout:
# ID 0 — overall deployment (phases, shown as % complete)
# ID 1 — current phase items (child bar, shown as current item name)
function Set-OverallProgress {
param(
[string]$Status,
[int] $Percent
)
Write-Progress -Id 0 -Activity (T 'ProgOverall') -Status $Status -PercentComplete $Percent
}
function Set-PhaseProgress {
param(
[string]$Activity,
[string]$Status,
[int] $Current,
[int] $Total
)
$pct = if ($Total -gt 0) { [int](($Current / $Total) * 100) } else { 0 }
Write-Progress -Id 1 -ParentId 0 -Activity $Activity -Status $Status -PercentComplete $pct
}
function Clear-PhaseProgress {
Write-Progress -Id 1 -Activity ' ' -Completed
}
# ================================
# Summary Counters & Results
# ================================
$script:Summary = @{
AppsInstalled = 0
AppsFailed = 0
AppxRemoved = 0
CapabilitiesRemoved = 0
McAfeeRemoved = 0
HardeningApplied = 0
HardeningFailed = 0
}
$script:Results = [System.Collections.Generic.List[hashtable]]::new()
function Add-Result {
param(
[string]$Section,
[string]$Item,
[ValidateSet('OK','SKIPPED','WARN','FAILED')]
[string]$Status,
[string]$Detail = ''
)
$script:Results.Add(@{
Section = $Section
Item = $Item
Status = $Status
Detail = $Detail
})
}
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force
# Cache OS info once — used for edition-aware behavior throughout the script
$script:OsInfo = Get-CimInstance Win32_OperatingSystem
$script:OsBuild = [int]$script:OsInfo.BuildNumber
$script:IsHome = $script:OsInfo.Caption -match '\bHome\b'
$script:IsWin11 = $script:OsBuild -ge 22000
Write-Log "===== $(T 'Started') =====" -Level 'SECTION'
Write-Log "PowerShell : $($PSVersionTable.PSVersion)"
Write-Log "OS : $($script:OsInfo.Caption) (Build $script:OsBuild)"
Write-Log "Hostname : $env:COMPUTERNAME"
Write-Log "Language : $resolvedLang"
Write-Log "Log file : $LogPath"
Write-Log "HTML report : $ReportPath"
# ================================
# Helper Functions
# ================================
function Set-RegistryValue {
param(
[string]$Path,
[string]$Name,
[int] $Value
)
try {
if (-not (Test-Path $Path)) { New-Item -Path $Path -Force | Out-Null }
Set-ItemProperty -Path $Path -Name $Name -Value $Value -Type DWord -Force -ErrorAction Stop
Write-Log "$(T 'RegistryOK'): $Path\$Name = $Value" -Level 'SUCCESS'
Add-Result -Section (T 'PhaseConfig') -Item $Name -Status 'OK' -Detail "$Path = $Value"
$script:Summary.HardeningApplied++
}
catch {
Write-Log "$(T 'RegistryFail'): $Path\$Name - $($_.Exception.Message)" -Level 'WARN'
Add-Result -Section (T 'PhaseConfig') -Item $Name -Status 'WARN' -Detail $_.Exception.Message
$script:Summary.HardeningFailed++
}
}
# ================================
# Winget Management
# ================================
function Install-WingetIfNeeded {
# Minimum usable winget version (supports --source winget, --accept-source-agreements)
$minVersion = [Version]'1.2.0'
Set-PhaseProgress -Activity (T 'ProgWingetCheck') -Status (T 'Checking') -Current 1 -Total 3
# --- Check existing winget ---
$needsInstall = $false
$wingetCmd = Get-Command winget -ErrorAction SilentlyContinue
if (-not $wingetCmd) {
Write-Log (T 'WingetMissing') -Level 'WARN'
$needsInstall = $true
} else {
$rawVer = (winget --version 2>$null) -replace '[^\d\.]', ''
try {
if ([Version]$rawVer -lt $minVersion) {
Write-Log "$(T 'WingetOld'): v$rawVer (minimum $minVersion)" -Level 'WARN'
$needsInstall = $true
} else {
Write-Log "$(T 'WingetFound'): v$rawVer"
}
}
catch {
# Version string unparseable — assume it is adequate and continue
Write-Log "$(T 'WingetFound'): $rawVer"
}
}
if (-not $needsInstall) {
Clear-PhaseProgress
return $true
}
# --- Bootstrap Step 1: re-register existing package (works on most OEM builds) ---
Write-Log "$(T 'WingetBootstrap')..." -Level 'SECTION'
Set-PhaseProgress -Activity (T 'ProgWingetCheck') -Status (T 'WingetReRegister') -Current 2 -Total 3
try {
Write-Log (T 'WingetReRegister')
Add-AppxPackage -RegisterByFamilyName -MainPackage 'Microsoft.DesktopAppInstaller_8wekyb3d8bbwe' -ErrorAction Stop
Start-Sleep -Seconds 3
$null = Get-Command winget -ErrorAction Stop
Write-Log (T 'WingetBootOK') -Level 'SUCCESS'
Clear-PhaseProgress
return $true
}
catch {
Write-Log "Re-registration failed: $($_.Exception.Message)" -Level 'WARN'
}
# --- Bootstrap Step 2: download MSIX bundle from Microsoft ---
Set-PhaseProgress -Activity (T 'ProgWingetCheck') -Status (T 'WingetDownload') -Current 3 -Total 3
$tempPath = Join-Path $env:TEMP 'AppInstaller.msixbundle'
try {
Write-Log (T 'WingetDownload')
# Prefer BITS (handles resume on slow/interrupted connections); fall back to WebClient
if (Get-Command Start-BitsTransfer -ErrorAction SilentlyContinue) {
Start-BitsTransfer -Source 'https://aka.ms/getwinget' -Destination $tempPath -ErrorAction Stop
} else {
(New-Object System.Net.WebClient).DownloadFile('https://aka.ms/getwinget', $tempPath)
}
Add-AppxPackage -Path $tempPath -ErrorAction Stop
Start-Sleep -Seconds 3
$null = Get-Command winget -ErrorAction Stop
Write-Log (T 'WingetBootOK') -Level 'SUCCESS'
Clear-PhaseProgress
return $true
}
catch {
Write-Log "$(T 'WingetBootFail'): $($_.Exception.Message)" -Level 'ERROR'
return $false
}
finally {
Remove-Item $tempPath -Force -ErrorAction SilentlyContinue
Clear-PhaseProgress
}
}
function Initialize-WingetSources {
Write-Log (T 'ManagingSources')
try {
Set-PhaseProgress -Activity (T 'ProgSources') -Status (T 'ProgSourcesList') -Current 1 -Total 2
$sources = winget source list 2>$null
if ($sources -match 'msstore') {
# msstore present — extend to 3 steps
Set-PhaseProgress -Activity (T 'ProgSources') -Status (T 'RemovingMsstore') -Current 2 -Total 3
Write-Log (T 'RemovingMsstore')
winget source remove --name msstore 2>$null | Out-Null
Set-PhaseProgress -Activity (T 'ProgSources') -Status (T 'ProgSourcesUpdate') -Current 3 -Total 3
} else {
Set-PhaseProgress -Activity (T 'ProgSources') -Status (T 'ProgSourcesUpdate') -Current 2 -Total 2
}
Write-Log (T 'RefreshingSources')
winget source update --name winget 2>$null | Out-Null
}
catch {
Write-Log "$(T 'SourcesFailed'): $($_.Exception.Message)" -Level 'WARN'
}
finally {
Clear-PhaseProgress
}
}
# ================================
# Bloatware Removal
# ================================
function Remove-WingetApps {
param([string[]]$AppPatterns)
Write-Log "--- $(T 'ProgBloatware') ---" -Level 'SECTION'
# Winget exit codes that mean "nothing to uninstall" — treat as SKIPPED, not WARN
$notFoundCodes = @(
-1978335212, # 0x8A15002C no package found to uninstall
-1978335189, # 0x8A15002B package not applicable / already gone
-1978334966 # 0x8A15010A no installed package found
)
$total = $AppPatterns.Count
$current = 0
foreach ($pattern in $AppPatterns) {
$current++
Set-PhaseProgress -Activity (T 'ProgBloatware') `
-Status "$(T 'Checking'): $pattern" `
-Current $current -Total $total
Write-Log "$(T 'Checking'): $pattern"
try {
$found = winget list --name "$pattern" --accept-source-agreements 2>$null |
Where-Object { $_ -and $_ -notmatch 'Name\s+Id\s+Version' -and $_.Trim() }
if (-not $found) {
Write-Log "$(T 'NotFound'): $pattern"
Add-Result -Section (T 'PhaseBloatware') -Item $pattern -Status 'SKIPPED' -Detail (T 'NotInstalled')
continue
}
Set-PhaseProgress -Activity (T 'ProgBloatware') `
-Status "$(T 'Removing'): $pattern" `
-Current $current -Total $total
winget uninstall --name "$pattern" --silent --force --accept-source-agreements 2>&1 | Out-Null
if ($LASTEXITCODE -eq 0) {
Write-Log "$(T 'Removed'): $pattern" -Level 'SUCCESS'
Add-Result -Section (T 'PhaseBloatware') -Item $pattern -Status 'OK' -Detail (T 'Removed')
} elseif ($LASTEXITCODE -in $notFoundCodes) {
Write-Log "$(T 'NotFound'): $pattern"
Add-Result -Section (T 'PhaseBloatware') -Item $pattern -Status 'SKIPPED' -Detail (T 'NotInstalled')
} else {
Write-Log "$(T 'RemoveExitCode') $LASTEXITCODE for: $pattern" -Level 'WARN'
Add-Result -Section (T 'PhaseBloatware') -Item $pattern -Status 'WARN' -Detail "$(T 'RemoveExitCode') $LASTEXITCODE"
}
}
catch {
Write-Log "$(T 'RemoveError') $pattern`: $($_.Exception.Message)" -Level 'ERROR'
Add-Result -Section (T 'PhaseBloatware') -Item $pattern -Status 'FAILED' -Detail $_.Exception.Message
}
}
Clear-PhaseProgress
}
function Remove-AppxPackages {
Write-Log "--- $(T 'ProgAppx') ---" -Level 'SECTION'
$packagesToRemove = @(
'*Microsoft.OutlookForWindows*',
'*Clipchamp*',
'*MicrosoftFamily*',
'*OneDrive*',
'*LinkedIn*',
'*Xbox*',
'*Skype*',
'*MixedReality*',
'*RemoteDesktop*',
'*QuickAssist*',
'*Microsoft.Copilot*',
'*Microsoft.Teams*'
)
$total = $packagesToRemove.Count
$current = 0
foreach ($pattern in $packagesToRemove) {
$current++
$label = $pattern.Replace('*','')
Set-PhaseProgress -Activity (T 'ProgAppx') -Status $label -Current $current -Total $total
try {
$removed = 0
$pkgs = Get-AppxPackage -AllUsers -Name $pattern -ErrorAction SilentlyContinue
foreach ($pkg in $pkgs) {
Write-Log "$(T 'AppxRemoving'): $($pkg.Name)"
Remove-AppxPackage -Package $pkg.PackageFullName -AllUsers -ErrorAction SilentlyContinue
$script:Summary.AppxRemoved++
$removed++
}
$provPkgs = Get-AppxProvisionedPackage -Online -ErrorAction SilentlyContinue |
Where-Object { $_.DisplayName -like $pattern }
foreach ($pkg in $provPkgs) {
Write-Log "$(T 'AppxProvRemoving'): $($pkg.DisplayName)"
Remove-AppxProvisionedPackage -Online -PackageName $pkg.PackageName -ErrorAction SilentlyContinue
$script:Summary.AppxRemoved++
$removed++
}
$status = if ($removed -gt 0) { 'OK' } else { 'SKIPPED' }
$detail = if ($removed -gt 0) { "$(T 'Removed') $removed" } else { T 'NotInstalled' }
Add-Result -Section (T 'ProgAppx') -Item $label -Status $status -Detail $detail
}
catch {
Write-Log "$(T 'RemoveError') $pattern`: $($_.Exception.Message)" -Level 'WARN'
Add-Result -Section (T 'ProgAppx') -Item $label -Status 'WARN' -Detail $_.Exception.Message
}
}
Clear-PhaseProgress
}
function Remove-WindowsCapabilities {
Write-Log "--- $(T 'ProgCaps') ---" -Level 'SECTION'
$capabilitiesToRemove = @(
'App.Support.QuickAssist~~~~0.0.1.0',
'App.Xbox.TCUI~~~~0.0.1.0',
'App.XboxGameOverlay~~~~0.0.1.0',
'App.XboxSpeechToTextOverlay~~~~0.0.1.0',
'OpenSSH.Client~~~~0.0.1.0'
)
# Get-WindowsCapability requires Windows Update to be accessible.
# On Home with metered connections, WSUS-redirected builds, or disabled WU it returns
# $null silently and produces misleading SKIPPED results — guard against that.
$wuSvc = Get-Service -Name wuauserv -ErrorAction SilentlyContinue
$wuAccessible = $wuSvc -and $wuSvc.StartType -ne 'Disabled'
if (-not $wuAccessible) {
Write-Log (T 'CapWuUnavail') -Level 'WARN'
foreach ($cap in $capabilitiesToRemove) {
Add-Result -Section (T 'ProgCaps') -Item $cap -Status 'SKIPPED' -Detail (T 'CapWuUnavail')
}
Clear-PhaseProgress
return
}
$total = $capabilitiesToRemove.Count
$current = 0
foreach ($cap in $capabilitiesToRemove) {
$current++
Set-PhaseProgress -Activity (T 'ProgCaps') -Status $cap -Current $current -Total $total
try {
$state = Get-WindowsCapability -Online -Name $cap -ErrorAction SilentlyContinue
if ($state -and $state.State -eq 'Installed') {
Write-Log "$(T 'CapRemoving'): $cap"
Remove-WindowsCapability -Online -Name $cap -ErrorAction SilentlyContinue | Out-Null
$script:Summary.CapabilitiesRemoved++
Add-Result -Section (T 'ProgCaps') -Item $cap -Status 'OK' -Detail (T 'Removed')
} else {
Write-Log "$(T 'NotInstalled'): $cap"
Add-Result -Section (T 'ProgCaps') -Item $cap -Status 'SKIPPED' -Detail (T 'NotInstalled')
}
}
catch {
Write-Log "$(T 'CapError') $cap`: $($_.Exception.Message)" -Level 'WARN'
Add-Result -Section (T 'ProgCaps') -Item $cap -Status 'WARN' -Detail $_.Exception.Message
}
}
Clear-PhaseProgress
}
function Remove-McAfeeProducts {
Write-Log "--- $(T 'ProgMcAfee') ---" -Level 'SECTION'
Set-PhaseProgress -Activity (T 'ProgMcAfee') -Status (T 'Checking') -Current 1 -Total 2
$uninstallPaths = @(
'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*',
'HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
)
$mcafeeEntries = foreach ($path in $uninstallPaths) {
Get-ItemProperty $path -ErrorAction SilentlyContinue |
Where-Object { $_.DisplayName -like '*McAfee*' }
}
if (-not $mcafeeEntries) {
Write-Log (T 'McAfeeNone')
Add-Result -Section (T 'ProgMcAfee') -Item 'McAfee' -Status 'SKIPPED' -Detail (T 'NotInstalled')
Clear-PhaseProgress
return
}
$total = @($mcafeeEntries).Count
$current = 0
foreach ($entry in $mcafeeEntries) {
$current++
$displayName = $entry.DisplayName
$uninstallString = $entry.UninstallString
Set-PhaseProgress -Activity (T 'ProgMcAfee') -Status $displayName -Current $current -Total $total
Write-Log "$(T 'McAfeeFound'): $displayName"
if (-not $uninstallString) {
Write-Log "$(T 'McAfeeNoStr') for $displayName" -Level 'WARN'
Add-Result -Section (T 'ProgMcAfee') -Item $displayName -Status 'WARN' -Detail (T 'McAfeeNoStr')
continue
}
try {
if ($uninstallString -match '^"([^"]+)"\s*(.*)$') {
$exe = $Matches[1]
$uninstallArgs = $Matches[2]
} else {
$parts = $uninstallString.Split(' ', 2)
$exe = $parts[0]
$uninstallArgs = if ($parts.Length -gt 1) { $parts[1] } else { '' }
}
if ($uninstallArgs -notmatch '/S|/silent|/quiet') { $uninstallArgs += ' /S /quiet' }
Write-Log "$(T 'McAfeeUninstall'): $displayName"
Start-Process -FilePath $exe -ArgumentList $uninstallArgs -Wait -WindowStyle Hidden -ErrorAction Stop
Write-Log "$(T 'McAfeeRemoved'): $displayName" -Level 'SUCCESS'
$script:Summary.McAfeeRemoved++
Add-Result -Section (T 'ProgMcAfee') -Item $displayName -Status 'OK' -Detail (T 'McAfeeRemoved')
}
catch {
Write-Log "$(T 'McAfeeFailed') $displayName`: $($_.Exception.Message)" -Level 'ERROR'
Add-Result -Section (T 'ProgMcAfee') -Item $displayName -Status 'FAILED' -Detail $_.Exception.Message
}
}
Clear-PhaseProgress
}
# ================================
# Application Installation
# ================================
function Install-StandardApps {
Write-Log "--- $(T 'ProgApps') ---" -Level 'SECTION'
$alreadyInstalledCode = -1978335189 # winget 0x8A15002B
# Winget exit codes that indicate a transient network problem — worth retrying
$networkErrorCodes = @(
-1978334967, # 0x8A150109 winget download failed
-1978334966, # 0x8A15010A winget network timeout
-2147012887, # 0x80072EE9 connection reset by peer
-2147012873, # 0x80072EF7 DNS name not resolved
-2147012867, # 0x80072EFD connection refused
-2147012889 # 0x80072EE7 InternetOpenUrl failed / WinHTTP unknown error
)
$maxRetries = 2
$retryDelaySec = 10
$appsToInstall = @(
# ---- Security & Maintenance ----
@{ Id = 'Malwarebytes.Malwarebytes'; Name = 'Malwarebytes' },
@{ Id = 'BleachBit.BleachBit'; Name = 'BleachBit' },
# ---- Browsers & Productivity ----
@{ Id = 'Google.Chrome'; Name = 'Google Chrome' },
@{ Id = 'Adobe.Acrobat.Reader.64-bit'; Name = 'Adobe Acrobat Reader (64-bit)' },
@{ Id = '7zip.7zip'; Name = '7-Zip' },
@{ Id = 'VideoLAN.VLC'; Name = 'VLC Media Player' },
# ---- .NET Runtimes ----
@{ Id = 'Microsoft.DotNet.Framework.4.8'; Name = '.NET Framework 4.8' },
@{ Id = 'Microsoft.DotNet.DesktopRuntime.6'; Name = '.NET 6 Desktop Runtime' },
@{ Id = 'Microsoft.DotNet.DesktopRuntime.7'; Name = '.NET 7 Desktop Runtime' },
@{ Id = 'Microsoft.DotNet.DesktopRuntime.8'; Name = '.NET 8 Desktop Runtime' },
# ---- Visual C++ Redistributables ----
@{ Id = 'Microsoft.VCRedist.2015+.x64'; Name = 'VC++ 2015-2022 Redist (x64)' },
@{ Id = 'Microsoft.VCRedist.2015+.x86'; Name = 'VC++ 2015-2022 Redist (x86)' }
)
$total = $appsToInstall.Count
$current = 0
foreach ($app in $appsToInstall) {
$current++
Set-PhaseProgress -Activity (T 'ProgApps') `
-Status "$(T 'Installing'): $($app.Name) ($current/$total)" `
-Current $current -Total $total
Write-Log "$(T 'Installing'): $($app.Name) [$($app.Id)]"
try {
$attempt = 0
$exitCode = -1
$wingetOut = $null
do {
$attempt++
# Capture output rather than discarding it — logged on failure
$wingetOut = winget install --id $app.Id --source winget `
--accept-package-agreements --accept-source-agreements `
--silent 2>&1
$exitCode = $LASTEXITCODE
if ($exitCode -eq 0 -or $exitCode -eq $alreadyInstalledCode) { break }
if ($attempt -le $maxRetries -and $exitCode -in $networkErrorCodes) {
Write-Log "$(T 'InstallRetrying') ($attempt/$maxRetries): $($app.Name) [exit $exitCode]" -Level 'WARN'
Start-Sleep -Seconds $retryDelaySec
} else {
break
}
} while ($true)
if ($exitCode -eq 0) {
Write-Log "$(T 'InstallOK'): $($app.Name)" -Level 'SUCCESS'
Add-Result -Section (T 'PhaseApps') -Item $app.Name -Status 'OK' -Detail (T 'InstallOK')
$script:Summary.AppsInstalled++
} elseif ($exitCode -eq $alreadyInstalledCode) {
Write-Log "$(T 'AlreadyInstalled'): $($app.Name)" -Level 'SUCCESS'
Add-Result -Section (T 'PhaseApps') -Item $app.Name -Status 'OK' -Detail (T 'AlreadyInstalled')
$script:Summary.AppsInstalled++
} else {
# Map exit code to a human-readable reason.
# Using switch($int) avoids hashtable string/int key-type ambiguity.
# Network codes here cover the "all retries exhausted" path.
$failReason = switch ($exitCode) {
-1978335215 { 'Installer hash mismatch — retry later or check proxy/AV' } # 0x8A150011
-1978335212 { 'Package not found in winget source (ID may have changed)' } # 0x8A15002C
-1978334960 { 'Installer blocked by security policy' } # 0x8A150110
-1978335132 { 'Installer requires reboot before continuing' } # 0x8A150064
-1978334967 { 'Network failure — download failed (all retries exhausted)' } # 0x8A150109
-1978334966 { 'Network failure — timed out (all retries exhausted)' } # 0x8A15010A
-2147012887 { 'Network failure — connection reset (all retries exhausted)' } # 0x80072EE9
-2147012873 { 'Network failure — DNS not resolved (all retries exhausted)' } # 0x80072EF7
-2147012867 { 'Network failure — connection refused (all retries exhausted)' } # 0x80072EFD
-2147012889 { 'Network failure — WinHTTP error (all retries exhausted)' } # 0x80072EE7
default { "Exit code $exitCode" }
}
Write-Log "$(T 'InstallFail'): $($app.Name) - $failReason" -Level 'WARN'
# Log last clean lines of winget output — strip progress-bar/spinner noise
$diagLines = ($wingetOut | Where-Object { "$_".Trim() }) | Select-Object -Last 8
foreach ($line in $diagLines) {
$clean = ("$line" -replace '[^ -~]', '').Trim()
if ($clean.Length -lt 8) { continue } # spinner chars: \|/-
if ($clean -match '^[\|/\-]+$') { continue } # pure spinner frame
if ($clean -match '^\s*\d+\s*MB') { continue } # "141 MB / 143 MB" lines
Write-Log " $clean" -Level 'WARN'
}
Add-Result -Section (T 'PhaseApps') -Item $app.Name -Status 'WARN' -Detail $failReason
$script:Summary.AppsFailed++
}
}
catch {
Write-Log "$(T 'InstallError') $($app.Name): $($_.Exception.Message)" -Level 'ERROR'
Add-Result -Section (T 'PhaseApps') -Item $app.Name -Status 'FAILED' -Detail $_.Exception.Message
$script:Summary.AppsFailed++
}
}
Clear-PhaseProgress
Write-Log "$(T 'PhaseApps'): $($script:Summary.AppsInstalled)/$total OK, $($script:Summary.AppsFailed) failed."
}
# ================================
# System Configuration
# ================================
function Set-SystemConfiguration {
Write-Log "--- $(T 'ProgConfig') ---" -Level 'SECTION'
# Flag policy-only keys — on Home edition these write successfully but have no effect.
# We log a WARN rather than SUCCESS so the report reflects reality.
$configItems = @(
@{ Path = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\DataCollection'; Name = 'AllowTelemetry'; Value = 0; PolicyOnly = $true },
@{ Path = 'HKLM:\SOFTWARE\Microsoft\Windows\Windows Error Reporting'; Name = 'Disabled'; Value = 1; PolicyOnly = $false },
@{ Path = 'HKLM:\SOFTWARE\Microsoft\SQMClient\Windows'; Name = 'CEIPEnable'; Value = 0; PolicyOnly = $false },
@{ Path = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\AdvertisingInfo'; Name = 'DisabledByGroupPolicy'; Value = 1; PolicyOnly = $true }
)
$total = $configItems.Count
$current = 0
foreach ($item in $configItems) {
$current++
Set-PhaseProgress -Activity (T 'ProgConfig') -Status $item.Name -Current $current -Total $total
if ($item.PolicyOnly -and $script:IsHome) {
Write-Log "$(T 'HomeEditionNote'): $($item.Name)" -Level 'WARN'
}
Set-RegistryValue -Path $item.Path -Name $item.Name -Value $item.Value