forked from jacquindev/windots
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSetup.ps1
More file actions
2384 lines (2138 loc) · 98 KB
/
Setup.ps1
File metadata and controls
2384 lines (2138 loc) · 98 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
<#PSScriptInfo
.VERSION 1.3.2
.GUID ccb5be4c-ea07-4c45-a5b4-6310df24e2bc
.AUTHOR eagarcia@techforexcellence.org
.COMPANYNAME
.COPYRIGHT 2025 Jacquin Moon. All rights reserved. (Original Author: jacquindev@outlook.com)
.TAGS windots dotfiles
.LICENSEURI https://github.com/XcluEzy7/windots/blob/main/LICENSE
.PROJECTURI https://github.com/XcluEzy7/windots
.ICONURI
.EXTERNALMODULEDEPENDENCIES
.REQUIREDSCRIPTS
.EXTERNALSCRIPTDEPENDENCIES
.RELEASENOTES
Version 1.3.2 - Updated by XcluEzy7
- Enhanced selective installation features
- Improved environment variable expansion
- Added global access and tab completion
- Automatic privilege escalation with gsudo
- Original script by Jacquin Moon (jacquindev@outlook.com)
.PRIVATEDATA
#>
#Requires -Version 7
<#
.DESCRIPTION
Setup script for Windows 11 Machine.
#>
Param(
[switch]$Force,
[switch]$Packages,
[switch]$PowerShell,
[switch]$Git,
[switch]$Symlinks,
[switch]$Environment,
[switch]$Addons,
[switch]$VSCode,
[switch]$Themes,
[switch]$Miscellaneous,
[switch]$Komorebi,
[switch]$NerdFonts,
[switch]$WSL,
[switch]$Updates
)
# CRITICAL: Handle Updates parameter FIRST - before any other processing
# This must be the very first check after Param block to ensure Updates mode runs exclusively
if ($Updates) {
$updateScriptPath = Join-Path $PSScriptRoot "updateApps.ps1"
if (Test-Path $updateScriptPath) {
Write-Host "Running application updates..." -ForegroundColor Cyan
# Pass through any package manager switches if they exist
# Note: Setup.ps1 doesn't have these switches, but updateApps.ps1 can be called directly
& $updateScriptPath
$exitCode = $LASTEXITCODE
exit $exitCode
} else {
Write-Error "Update script not found: $updateScriptPath"
exit 1
}
}
$VerbosePreference = "SilentlyContinue"
# Note: Updates mode doesn't require admin (Scoop must run as non-admin)
# Other operations require admin, so we check at runtime AFTER Updates check
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object System.Security.Principal.WindowsPrincipal($currentUser)
$isAdmin = $principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
Write-Error "This script requires administrator privileges. Please run as administrator or use gsudo."
Write-Host "For updates only, use: w11dot-setup -Updates" -ForegroundColor Yellow
exit 1
}
# Validate skip parameters - only one can be used at a time
$skipParams = @($Packages, $PowerShell, $Git, $Symlinks, $Environment, $Addons, $VSCode, $Themes, $Miscellaneous, $Komorebi, $NerdFonts, $WSL)
$skipCount = ($skipParams | Where-Object { $_ -eq $true }).Count
if ($skipCount -gt 1) {
Write-Error "Only one skip parameter can be used at a time. Please specify only one section to run."
exit 1
}
# Determine which section to run (if any)
$runSection = $null
if ($Packages) { $runSection = "Packages" }
elseif ($PowerShell) { $runSection = "PowerShell" }
elseif ($Git) { $runSection = "Git" }
elseif ($Symlinks) { $runSection = "Symlinks" }
elseif ($Environment) { $runSection = "Environment" }
elseif ($Addons) { $runSection = "Addons" }
elseif ($VSCode) { $runSection = "VSCode" }
elseif ($Themes) { $runSection = "Themes" }
elseif ($Miscellaneous) { $runSection = "Miscellaneous" }
elseif ($Komorebi) { $runSection = "Komorebi" }
elseif ($NerdFonts) { $runSection = "NerdFonts" }
elseif ($WSL) { $runSection = "WSL" }
# Helper function to check if a section should run
function Should-RunSection {
param([string]$SectionName)
if ($null -eq $runSection) { return $true } # Full install
return ($runSection -eq $SectionName)
}
# Tracking variables for summary
$script:setupSummary = @{
Created = @()
Updated = @()
Exists = @()
Failed = @()
Skipped = @()
}
########################################################################################################################
### HELPER FUNCTIONS ###
########################################################################################################################
function Write-TitleBox {
param ([string]$Title, [string]$BorderChar = "*", [int]$Padding = 10)
$Title = $Title.ToUpper()
$titleLength = $Title.Length
$boxWidth = $titleLength + ($Padding * 2) + 2
$borderLine = $BorderChar * $boxWidth
$paddingLine = $BorderChar + (" " * ($boxWidth - 2)) + $BorderChar
$titleLine = $BorderChar + (" " * $Padding) + $Title + (" " * $Padding) + $BorderChar
''
Write-Host $borderLine -ForegroundColor Cyan
Write-Host $paddingLine -ForegroundColor Cyan
Write-Host $titleLine -ForegroundColor Cyan
Write-Host $paddingLine -ForegroundColor Cyan
Write-Host $borderLine -ForegroundColor Cyan
''
}
# Source:
# - https://stackoverflow.com/questions/2688547/multiple-foreground-colors-in-powershell-in-one-command
function Write-ColorText {
param ([string]$Text, [switch]$NoNewLine)
$hostColor = $Host.UI.RawUI.ForegroundColor
$Text.Split( [char]"{", [char]"}" ) | ForEach-Object { $i = 0; } {
if ($i % 2 -eq 0) { Write-Host $_ -NoNewline }
else {
if ($_ -in [enum]::GetNames("ConsoleColor")) {
$Host.UI.RawUI.ForegroundColor = ($_ -as [System.ConsoleColor])
}
}
$i++
}
if (!$NoNewLine) { Write-Host }
$Host.UI.RawUI.ForegroundColor = $hostColor
}
function Add-ScoopBucket {
param ([string]$BucketName, [string]$BucketRepo)
$scoopDir = (Get-Command scoop.ps1 -ErrorAction SilentlyContinue).Source | Split-Path | Split-Path
if (!(Test-Path "$scoopDir\buckets\$BucketName" -PathType Container)) {
if ($BucketRepo) {
scoop bucket add $BucketName $BucketRepo
} else {
scoop bucket add $BucketName
}
} else {
Write-ColorText "{Blue}[bucket] {Magenta}scoop: {Yellow}(exists) {Gray}$BucketName"
}
}
function Install-ScoopApp {
param ([string]$Package, [switch]$Global, [array]$AdditionalArgs)
$scoopInfo = scoop info $Package
$isInstalled = $scoopInfo.Installed
if (!$isInstalled) {
$scoopCmd = "scoop install $Package"
if ($Global) { $scoopCmd += " -g" }
if ($AdditionalArgs.Count -ge 1) {
$AdditionalArgs = $AdditionalArgs -join ' '
$scoopCmd += " $AdditionalArgs"
}
''; Invoke-Expression "$scoopCmd"; ''
} elseif ($Force) {
# Force reinstall
$scoopCmd = "scoop uninstall $Package"
if ($Global) { $scoopCmd += " -g" }
Invoke-Expression "$scoopCmd >`$null 2>&1"
$scoopCmd = "scoop install $Package"
if ($Global) { $scoopCmd += " -g" }
if ($AdditionalArgs.Count -ge 1) {
$AdditionalArgs = $AdditionalArgs -join ' '
$scoopCmd += " $AdditionalArgs"
}
''; Invoke-Expression "$scoopCmd"; ''
Write-ColorText "{Blue}[package] {Magenta}scoop: {Green}(reinstalled) {Gray}$Package"
} else {
Write-ColorText "{Blue}[package] {Magenta}scoop: {Yellow}(exists) {Gray}$Package"
}
}
function Install-WinGetApp {
param ([string]$PackageID, [array]$AdditionalArgs, [string]$Source)
winget list --exact -q $PackageID | Out-Null
$isInstalled = $?
if (!$isInstalled) {
$wingetCmd = "winget install $PackageID"
if ($AdditionalArgs.Count -ge 1) {
$AdditionalArgs = $AdditionalArgs -join ' '
$wingetCmd += " $AdditionalArgs"
}
if ($Source -eq "msstore") { $wingetCmd += " --source msstore" }
else { $wingetCmd += " --source winget" }
Invoke-Expression "$wingetCmd >`$null 2>&1"
if ($LASTEXITCODE -eq 0) {
Write-ColorText "{Blue}[package] {Magenta}winget: {Green}(success) {Gray}$PackageID"
} else {
Write-ColorText "{Blue}[package] {Magenta}winget: {Red}(failed) {Gray}$PackageID"
}
} elseif ($Force) {
# Force reinstall
$wingetCmd = "winget install $PackageID --force"
if ($AdditionalArgs.Count -ge 1) {
$AdditionalArgs = $AdditionalArgs -join ' '
$wingetCmd += " $AdditionalArgs"
}
if ($Source -eq "msstore") { $wingetCmd += " --source msstore" }
else { $wingetCmd += " --source winget" }
Invoke-Expression "$wingetCmd >`$null 2>&1"
if ($LASTEXITCODE -eq 0) {
Write-ColorText "{Blue}[package] {Magenta}winget: {Green}(reinstalled) {Gray}$PackageID"
} else {
Write-ColorText "{Blue}[package] {Magenta}winget: {Red}(failed) {Gray}$PackageID"
}
} else {
Write-ColorText "{Blue}[package] {Magenta}winget: {Yellow}(exists) {Gray}$PackageID"
}
}
function Install-ChocoApp {
param ([string]$Package, [string]$Version, [array]$AdditionalArgs)
$chocoList = choco list $Package
$isInstalled = $chocoList -notlike "0 packages installed."
if (!$isInstalled) {
$chocoCmd = "choco install $Package"
if ($Version) {
$pkgVer = "--version=$Version"
$chocoCmd += " $pkgVer"
}
if ($AdditionalArgs.Count -ge 1) {
$AdditionalArgs = $AdditionalArgs -join ' '
$chocoCmd += " $AdditionalArgs"
}
Invoke-Expression "$chocoCmd >`$null 2>&1"
if ($LASTEXITCODE -eq 0) {
Write-ColorText "{Blue}[package] {Magenta}choco: {Green}(success) {Gray}$Package"
} else {
Write-ColorText "{Blue}[package] {Magenta}choco: {Red}(failed) {Gray}$Package"
}
} elseif ($Force) {
# Force reinstall
$chocoCmd = "choco install $Package --force"
if ($Version) {
$pkgVer = "--version=$Version"
$chocoCmd += " $pkgVer"
}
if ($AdditionalArgs.Count -ge 1) {
$AdditionalArgs = $AdditionalArgs -join ' '
$chocoCmd += " $AdditionalArgs"
}
Invoke-Expression "$chocoCmd >`$null 2>&1"
if ($LASTEXITCODE -eq 0) {
Write-ColorText "{Blue}[package] {Magenta}choco: {Green}(reinstalled) {Gray}$Package"
} else {
Write-ColorText "{Blue}[package] {Magenta}choco: {Red}(failed) {Gray}$Package"
}
} else {
Write-ColorText "{Blue}[package] {Magenta}choco: {Yellow}(exists) {Gray}$Package"
}
}
function Initialize-PowerShellPrerequisites {
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Gray}Initializing PowerShell 5.1 prerequisites..."
# All prerequisites must be initialized in PowerShell 5.1 (Windows PowerShell)
# Build a comprehensive script to run in PowerShell 5.1
$prereqScript = @"
# Enforce TLS 1.2 for secure connections to PowerShell Gallery
try {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Write-Output 'TLS12:SUCCESS'
} catch {
Write-Output "TLS12:ERROR:`$(`$_.Exception.Message)"
}
# Register and trust PSGallery repository
`$psGalleryRegistered = `$false
try {
`$psGallery = Get-PSRepository -Name PSGallery -ErrorAction SilentlyContinue
if (!`$psGallery) {
# Try to register PSGallery
try {
Register-PSRepository -Default -ErrorAction Stop
`$psGalleryRegistered = `$true
Write-Output 'PSGALLERY:REGISTERED'
} catch {
try {
Register-PSRepository -Name PSGallery -SourceLocation 'https://www.powershellgallery.com/api/v2' -InstallationPolicy Trusted -ErrorAction Stop
`$psGalleryRegistered = `$true
Write-Output 'PSGALLERY:REGISTERED'
} catch {
Write-Output "PSGALLERY:DEFERRED:`$(`$_.Exception.Message)"
}
}
} else {
`$psGalleryRegistered = `$true
Write-Output 'PSGALLERY:EXISTS'
# Check if PSGallery is properly configured
if (!`$psGallery.SourceLocation -or `$psGallery.SourceLocation -eq '') {
try {
Unregister-PSRepository -Name PSGallery -ErrorAction SilentlyContinue
Register-PSRepository -Name PSGallery -SourceLocation 'https://www.powershellgallery.com/api/v2' -InstallationPolicy Trusted -ErrorAction Stop
Write-Output 'PSGALLERY:REREGISTERED'
} catch {
Write-Output "PSGALLERY:REREGISTER_FAILED:`$(`$_.Exception.Message)"
}
}
}
# Set PSGallery as trusted
if (`$psGalleryRegistered) {
`$psGallery = Get-PSRepository -Name PSGallery -ErrorAction SilentlyContinue
if (`$psGallery -and `$psGallery.InstallationPolicy -ne 'Trusted') {
Set-PSRepository -Name PSGallery -InstallationPolicy Trusted -ErrorAction Stop
Write-Output 'PSGALLERY:TRUSTED'
}
}
} catch {
Write-Output "PSGALLERY:ERROR:`$(`$_.Exception.Message)"
}
"@
# Execute prerequisites script in PowerShell 5.1
$prereqResults = & powershell.exe -NoProfile -Command $prereqScript
# Parse results
foreach ($result in $prereqResults) {
if ($result -match '^TLS12:') {
if ($result -eq 'TLS12:SUCCESS') {
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Green}(success) {Gray}TLS 1.2 enforced (PowerShell 5.1)"
} else {
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Yellow}(warning) {Gray}Could not enforce TLS 1.2: $($result -replace 'TLS12:ERROR:', '')"
}
} elseif ($result -match '^PSGALLERY:') {
if ($result -eq 'PSGALLERY:REGISTERED') {
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Green}(success) {Gray}PSGallery repository registered (PowerShell 5.1)"
} elseif ($result -eq 'PSGALLERY:EXISTS') {
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Yellow}(exists) {Gray}PSGallery repository (PowerShell 5.1)"
} elseif ($result -eq 'PSGALLERY:REREGISTERED') {
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Green}(success) {Gray}PSGallery repository re-registered (PowerShell 5.1)"
} elseif ($result -eq 'PSGALLERY:TRUSTED') {
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Green}(success) {Gray}PSGallery set as trusted (PowerShell 5.1)"
} elseif ($result -match '^PSGALLERY:DEFERRED:') {
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Yellow}(warning) {Gray}PSGallery registration deferred (NuGet provider required first): $($result -replace 'PSGALLERY:DEFERRED:', '')"
} elseif ($result -match '^PSGALLERY:') {
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Yellow}(warning) {Gray}PSGallery configuration: $($result -replace 'PSGALLERY:', '')"
}
}
}
# Install/Update NuGet provider in PowerShell 5.1 (required for module installation)
# Use manual bootstrap method since PowerShellGet may be broken
try {
# Check NuGet provider in PowerShell 5.1
$nugetCheckScript = @"
`$provider = Get-PackageProvider -Name NuGet -ListAvailable -ErrorAction SilentlyContinue |
Where-Object { [version]`$_.Version -ge [version]'2.8.5.201' } |
Sort-Object Version -Descending |
Select-Object -First 1
if (`$provider) {
Write-Output "EXISTS:`$(`$provider.Version)"
} else {
Write-Output 'NOT_FOUND'
}
"@
$nugetCheckResult = & powershell.exe -NoProfile -Command $nugetCheckScript
$nugetProvider = $null
if ($nugetCheckResult -match '^EXISTS:') {
$nugetVersion = $nugetCheckResult -replace 'EXISTS:', ''
$nugetProvider = @{ Version = $nugetVersion }
}
if (!$nugetProvider) {
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Gray}Installing NuGet provider (minimum 2.8.5.201) in PowerShell 5.1 via manual bootstrap..."
$nugetInstalled = $false
# Method 1: Try standard installation in PowerShell 5.1 (may fail if PowerShellGet is broken)
$nugetInstallScript1 = @"
try {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Scope CurrentUser -ErrorAction Stop | Out-Null
`$verify = Get-PackageProvider -Name NuGet -ListAvailable -ErrorAction SilentlyContinue |
Where-Object { [version]`$_.Version -ge [version]'2.8.5.201' } |
Select-Object -First 1
if (`$verify) {
Write-Output "SUCCESS:`$(`$verify.Version)"
} else {
Write-Output 'VERIFY_FAILED'
}
} catch {
Write-Output "ERROR:`$(`$_.Exception.Message)"
}
"@
try {
$installResult1 = & powershell.exe -NoProfile -Command $nugetInstallScript1
if ($installResult1 -match '^SUCCESS:') {
$nugetInstalled = $true
$installedVersion = $installResult1 -replace 'SUCCESS:', ''
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Green}(success) {Gray}NuGet provider $installedVersion installed via standard method (PowerShell 5.1)"
} elseif ($installResult1 -eq 'VERIFY_FAILED') {
throw "Installation completed but verification failed"
} else {
$errorMsg = $installResult1 -replace 'ERROR:', ''
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Yellow}(warning) {Gray}Standard installation failed, using manual bootstrap: $errorMsg"
throw $errorMsg
}
} catch {
# Method 2: Manual bootstrap - download and install NuGet provider directly
# This runs in the current PowerShell 7.x context to download files, then installs in PowerShell 5.1
try {
# Primary method: Download and run the official NuGet provider installer
# This is the most reliable method when PowerShellGet is broken
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Gray}Downloading NuGet provider installer..."
$nugetUrl = "https://oneget.org/nuget-2.8.5.201.exe"
$nugetInstaller = "$env:TEMP\nuget-installer.exe"
Invoke-WebRequest -Uri $nugetUrl -OutFile $nugetInstaller -UseBasicParsing -ErrorAction Stop
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Gray}Installing NuGet provider in PowerShell 5.1 (this may take a moment)..."
$installProcess = Start-Process -FilePath $nugetInstaller -ArgumentList "/quiet" -Wait -NoNewWindow -PassThru
if ($installProcess.ExitCode -eq 0 -or $installProcess.ExitCode -eq $null) {
# Give it a moment to register
Start-Sleep -Seconds 2
# Verify installation in PowerShell 5.1
$verifyScript = @"
`$verify = Get-PackageProvider -Name NuGet -ListAvailable -ErrorAction SilentlyContinue |
Where-Object { [version]`$_.Version -ge [version]'2.8.5.201' } |
Select-Object -First 1
if (`$verify) {
Write-Output "SUCCESS:`$(`$verify.Version)"
} else {
Write-Output 'VERIFY_FAILED'
}
"@
$verifyResult = & powershell.exe -NoProfile -Command $verifyScript
if ($verifyResult -match '^SUCCESS:') {
$nugetInstalled = $true
$installedVersion = $verifyResult -replace 'SUCCESS:', ''
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Green}(success) {Gray}NuGet provider $installedVersion installed (PowerShell 5.1)"
} else {
# Provider may need a PowerShell restart, but continue anyway
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Yellow}(warning) {Gray}NuGet provider installed but may require PowerShell 5.1 restart to be fully available"
$nugetInstalled = $true
}
} else {
throw "Installer exited with code $($installProcess.ExitCode)"
}
# Clean up
Remove-Item $nugetInstaller -Force -ErrorAction SilentlyContinue
} catch {
# Fallback: Try downloading from PowerShell Gallery API directly
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Yellow}(warning) {Gray}Installer method failed, trying package download: $_"
try {
# Determine provider assemblies directory (shared location for both PS versions)
$providerPath = "$env:USERPROFILE\AppData\Local\PackageManagement\ProviderAssemblies"
$nugetProviderPath = Join-Path $providerPath "nuget"
# Create directory if it doesn't exist
if (!(Test-Path $providerPath)) {
New-Item -ItemType Directory -Path $providerPath -Force | Out-Null
}
if (!(Test-Path $nugetProviderPath)) {
New-Item -ItemType Directory -Path $nugetProviderPath -Force | Out-Null
}
# Download NuGet provider package
$nugetPackageUrl = "https://www.powershellgallery.com/api/v2/package/NuGet/2.8.5.201"
$nugetPackageZip = "$env:TEMP\nuget-provider.zip"
Invoke-WebRequest -Uri $nugetPackageUrl -OutFile $nugetPackageZip -UseBasicParsing -ErrorAction Stop
Expand-Archive -Path $nugetPackageZip -DestinationPath "$env:TEMP\nuget-provider" -Force
# Copy provider DLL
$extractedPath = "$env:TEMP\nuget-provider"
$providerDll = Get-ChildItem -Path $extractedPath -Recurse -Filter "Microsoft.PackageManagement.NuGetProvider.dll" -ErrorAction SilentlyContinue | Select-Object -First 1
if ($providerDll) {
Copy-Item -Path $providerDll.FullName -Destination $nugetProviderPath -Force
# Verify in PowerShell 5.1
$verifyScript2 = @"
Import-PackageProvider -Name NuGet -Force -ErrorAction SilentlyContinue | Out-Null
`$verify = Get-PackageProvider -Name NuGet -ListAvailable -ErrorAction SilentlyContinue |
Where-Object { [version]`$_.Version -ge [version]'2.8.5.201' } |
Select-Object -First 1
if (`$verify) {
Write-Output "SUCCESS:`$(`$verify.Version)"
} else {
Write-Output 'VERIFY_FAILED'
}
"@
$verifyResult2 = & powershell.exe -NoProfile -Command $verifyScript2
if ($verifyResult2 -match '^SUCCESS:') {
$nugetInstalled = $true
$installedVersion2 = $verifyResult2 -replace 'SUCCESS:', ''
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Green}(success) {Gray}NuGet provider $installedVersion2 installed via package download (PowerShell 5.1)"
}
}
# Clean up
Remove-Item $nugetPackageZip -Force -ErrorAction SilentlyContinue
Remove-Item $extractedPath -Recurse -Force -ErrorAction SilentlyContinue
} catch {
throw "All bootstrap methods failed: $_"
}
}
}
if ($nugetInstalled) {
# Retry PSGallery registration in PowerShell 5.1 now that NuGet is available
$retryPSGalleryScript = @"
try {
`$psGallery = Get-PSRepository -Name PSGallery -ErrorAction SilentlyContinue
if (!`$psGallery) {
Register-PSRepository -Default -ErrorAction Stop
Set-PSRepository -Name PSGallery -InstallationPolicy Trusted -ErrorAction Stop
Write-Output 'PSGALLERY:REGISTERED'
} else {
Set-PSRepository -Name PSGallery -InstallationPolicy Trusted -ErrorAction Stop
Write-Output 'PSGALLERY:TRUSTED'
}
} catch {
Write-Output "PSGALLERY:ERROR:`$(`$_.Exception.Message)"
}
"@
$retryResult = & powershell.exe -NoProfile -Command $retryPSGalleryScript
if ($retryResult -eq 'PSGALLERY:REGISTERED') {
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Green}(success) {Gray}PSGallery repository registered (after NuGet installation, PowerShell 5.1)"
} elseif ($retryResult -eq 'PSGALLERY:TRUSTED') {
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Green}(success) {Gray}PSGallery set as trusted (PowerShell 5.1)"
} elseif ($retryResult -match '^PSGALLERY:ERROR:') {
$errorMsg = $retryResult -replace 'PSGALLERY:ERROR:', ''
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Yellow}(warning) {Gray}PSGallery registration still failed: $errorMsg"
}
} else {
throw "NuGet provider installation failed with all methods"
}
} else {
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Yellow}(exists) {Gray}NuGet provider $($nugetProvider.Version) (PowerShell 5.1)"
}
} catch {
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Red}(failed) {Gray}NuGet provider installation: $_"
$script:setupSummary.Failed += "PowerShell Prerequisite: NuGet provider"
}
# Note: PackageManagement and PowerShellGet are built into PowerShell 5.1
# We don't need to install them separately - they're already available
Write-ColorText "{Blue}[prerequisite] {Magenta}pwsh: {Yellow}(info) {Gray}PackageManagement and PowerShellGet are built into PowerShell 5.1"
''
}
function Install-PowerShellModule {
param ([string]$Module, [string]$Version, [array]$AdditionalArgs)
# Check if module is installed in PowerShell 5.1 (Windows PowerShell)
# Modules must be installed in PowerShell 5.1, not PowerShell 7.x
$ps51CheckScript = @"
`$module = Get-InstalledModule -Name '$Module' -ErrorAction SilentlyContinue
if (`$module) { Write-Output 'INSTALLED' } else { Write-Output 'NOT_INSTALLED' }
"@
$checkResult = & powershell.exe -NoProfile -Command $ps51CheckScript
$moduleInstalled = ($checkResult -eq 'INSTALLED')
if (!$moduleInstalled) {
try {
# Build Install-Module command for PowerShell 5.1
$installCmd = "Install-Module -Name '$Module' -Scope CurrentUser -Force -AllowClobber -SkipPublisherCheck -ErrorAction Stop"
if ($null -ne $Version) {
$installCmd += " -RequiredVersion '$Version'"
}
# Add additional arguments if provided
if ($AdditionalArgs.Count -ge 1) {
for ($i = 0; $i -lt $AdditionalArgs.Count; $i++) {
if ($AdditionalArgs[$i] -match '^-') {
$paramName = $AdditionalArgs[$i].TrimStart('-')
if ($i + 1 -lt $AdditionalArgs.Count -and $AdditionalArgs[$i + 1] -notmatch '^-') {
$paramValue = $AdditionalArgs[$i + 1]
$installCmd += " -$paramName '$paramValue'"
$i++
} else {
$installCmd += " -$paramName"
}
}
}
}
# Execute installation in PowerShell 5.1
$installScript = @"
try {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$installCmd
`$verify = Get-InstalledModule -Name '$Module' -ErrorAction SilentlyContinue
if (`$verify) { Write-Output 'SUCCESS' } else { Write-Output 'VERIFY_FAILED' }
} catch {
Write-Output "ERROR: `$(`$_.Exception.Message)"
}
"@
$installResult = & powershell.exe -NoProfile -Command $installScript
if ($installResult -eq 'SUCCESS') {
Write-ColorText "{Blue}[module] {Magenta}pwsh: {Green}(success) {Gray}$Module {DarkGray}(installed in PowerShell 5.1)"
} elseif ($installResult -eq 'VERIFY_FAILED') {
throw "Module installation completed but verification failed"
} else {
throw $installResult
}
} catch {
Write-ColorText "{Blue}[module] {Magenta}pwsh: {Red}(failed) {Gray}$Module {DarkGray}Error: $_"
$script:setupSummary.Failed += "PowerShell Module: $Module"
}
} elseif ($Force) {
# Force reinstall
try {
$installCmd = "Install-Module -Name '$Module' -Scope CurrentUser -Force -AllowClobber -SkipPublisherCheck -ErrorAction Stop"
if ($null -ne $Version) {
$installCmd += " -RequiredVersion '$Version'"
}
# Add additional arguments if provided
if ($AdditionalArgs.Count -ge 1) {
for ($i = 0; $i -lt $AdditionalArgs.Count; $i++) {
if ($AdditionalArgs[$i] -match '^-') {
$paramName = $AdditionalArgs[$i].TrimStart('-')
if ($i + 1 -lt $AdditionalArgs.Count -and $AdditionalArgs[$i + 1] -notmatch '^-') {
$paramValue = $AdditionalArgs[$i + 1]
$installCmd += " -$paramName '$paramValue'"
$i++
} else {
$installCmd += " -$paramName"
}
}
}
}
# Execute reinstallation in PowerShell 5.1
$reinstallScript = @"
try {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$installCmd
`$verify = Get-InstalledModule -Name '$Module' -ErrorAction SilentlyContinue
if (`$verify) { Write-Output 'SUCCESS' } else { Write-Output 'VERIFY_FAILED' }
} catch {
Write-Output "ERROR: `$(`$_.Exception.Message)"
}
"@
$reinstallResult = & powershell.exe -NoProfile -Command $reinstallScript
if ($reinstallResult -eq 'SUCCESS') {
Write-ColorText "{Blue}[module] {Magenta}pwsh: {Green}(reinstalled) {Gray}$Module {DarkGray}(installed in PowerShell 5.1)"
} elseif ($reinstallResult -eq 'VERIFY_FAILED') {
throw "Module reinstallation completed but verification failed"
} else {
throw $reinstallResult
}
} catch {
Write-ColorText "{Blue}[module] {Magenta}pwsh: {Red}(failed) {Gray}$Module {DarkGray}Error: $_"
$script:setupSummary.Failed += "PowerShell Module: $Module"
}
} else {
Write-ColorText "{Blue}[module] {Magenta}pwsh: {Yellow}(exists) {Gray}$Module {DarkGray}(in PowerShell 5.1)"
}
}
function Install-AppFromGitHub {
param ([string]$RepoName, [string]$FileName)
$release = "https://api.github.com/repos/$RepoName/releases"
$tag = (Invoke-WebRequest $release | ConvertFrom-Json)[0].tag_name
$downloadUrl = "https://github.com/$RepoName/releases/download/$tag/$FileName"
$downloadPath = (New-Object -ComObject Shell.Application).NameSpace('shell:Downloads').Self.Path
$downloadFile = "$downloadPath\$FileName"
(New-Object System.Net.WebClient).DownloadFile($downloadUrl, $downloadFile)
switch ($FileName.Split('.') | Select-Object -Last 1) {
"exe" {
Start-Process -FilePath "$downloadFile" -Wait
}
"msi" {
Start-Process -FilePath "$downloadFile" -Wait
}
"zip" {
$dest = "$downloadPath\$($FileName.Split('.'))"
Expand-Archive -Path "$downloadFile" -DestinationPath "$dest"
}
"7z" {
7z x -o"$downloadPath" -y "$downloadFile" | Out-Null
}
Default { break }
}
Remove-Item "$downloadFile" -Force -Recurse -ErrorAction SilentlyContinue
}
function Install-OnlineFile {
param ([string]$OutputDir, [string]$Url)
Invoke-WebRequest -Uri $Url -OutFile $OutputDir
}
function Refresh ([int]$Time) {
if (Get-Command choco -ErrorAction SilentlyContinue) {
switch -regex ($Time.ToString()) {
'1(1|2|3)$' { $suffix = 'th'; break }
'.?1$' { $suffix = 'st'; break }
'.?2$' { $suffix = 'nd'; break }
'.?3$' { $suffix = 'rd'; break }
default { $suffix = 'th'; break }
}
if (!(Get-Module -ListAvailable -Name "chocoProfile" -ErrorAction SilentlyContinue)) {
$chocoModule = "C:\ProgramData\chocolatey\helpers\chocolateyProfile.psm1"
if (Test-Path $chocoModule -PathType Leaf) {
Import-Module $chocoModule
}
}
Write-Verbose -Message "Refreshing environment variables from registry ($Time$suffix attempt)"
refreshenv | Out-Null
}
}
function Write-LockFile {
param (
[ValidateSet('winget', 'choco', 'scoop', 'modules')]
[Alias('s', 'p')][string]$PackageSource,
[Alias('f')][string]$FileName,
[Alias('o')][string]$OutputPath = "$PSScriptRoot\out"
)
$dest = "$OutputPath\$FileName"
switch ($PackageSource) {
"winget" {
if (!(Get-Command winget -ErrorAction SilentlyContinue)) { return }
winget export -o $dest | Out-Null
if ($LASTEXITCODE -eq 0) {
Write-ColorText "`n✔️ Packages installed by {Green}$PackageSource {Gray}are exported at {Red}$((Resolve-Path $dest).Path)"
}
Start-Sleep -Seconds 1
}
"choco" {
if (!(Get-Command choco -ErrorAction SilentlyContinue)) { return }
choco export $dest | Out-Null
if ($LASTEXITCODE -eq 0) {
Write-ColorText "`n✔️ Packages installed by {Green}$PackageSource {Gray}are exported at {Red}$((Resolve-Path $dest).Path)"
}
Start-Sleep -Seconds 1
}
"scoop" {
if (!(Get-Command scoop -ErrorAction SilentlyContinue)) { return }
scoop export -c > $dest
if ($LASTEXITCODE -eq 0) {
Write-ColorText "`n✔️ Packages installed by {Green}$PackageSource {Gray}are exported at {Red}$((Resolve-Path $dest).Path)"
}
Start-Sleep -Seconds 1
}
"modules" {
Get-InstalledModule | Select-Object -Property Name, Version | ConvertTo-Json -Depth 100 | Out-File $dest
if ($LASTEXITCODE -eq 0) {
Write-ColorText "`n✔️ {Green}PowerShell Modules {Gray}installed are exported at {Red}$((Resolve-Path $dest).Path)"
}
Start-Sleep -Seconds 1
}
}
}
function New-SymbolicLinks {
param (
[string]$Source,
[string]$Destination,
[switch]$Recurse
)
if (!(Test-Path $Source)) {
Write-ColorText "{Yellow}[symlink] {Gray}Source path does not exist: $Source"
$script:setupSummary.Skipped += "Symlinks from $Source (source not found)"
return
}
Get-ChildItem $Source -Recurse:$Recurse | Where-Object { !$_.PSIsContainer } | ForEach-Object {
$destinationPath = $_.FullName -replace [regex]::Escape($Source), $Destination
$destinationDir = Split-Path $destinationPath
# Create destination directory if it doesn't exist
if (!(Test-Path $destinationDir)) {
New-Item $destinationDir -ItemType Directory -Force -ErrorAction SilentlyContinue | Out-Null
}
# Check if destination already exists
if (Test-Path $destinationPath) {
$existingItem = Get-Item $destinationPath -ErrorAction SilentlyContinue
if ($existingItem.LinkType -eq 'SymbolicLink') {
# Already a symlink, check if it points to the right target
$targetPath = (Get-Item $destinationPath).Target
if ($targetPath -ne $_.FullName) {
# Wrong target, update it
Remove-Item $destinationPath -Force -ErrorAction SilentlyContinue
New-Item -ItemType SymbolicLink -Path $destinationPath -Target $($_.FullName) -Force -ErrorAction SilentlyContinue | Out-Null
$script:setupSummary.Updated += $destinationPath
Write-ColorText "{Blue}[symlink] {Yellow}(updated) {Green}$($_.FullName) {Yellow}--> {Gray}$destinationPath"
} else {
# Correct target, skip
$script:setupSummary.Exists += $destinationPath
Write-ColorText "{Blue}[symlink] {Yellow}(exists) {Gray}$destinationPath"
}
} else {
# Existing file/directory that's not a symlink - backup and replace
if ($Force) {
$backupPath = "$destinationPath.backup.$(Get-Date -Format 'yyyyMMdd-HHmmss')"
Write-ColorText "{Yellow}[symlink] {Gray}Backing up existing file: $backupPath"
Copy-Item $destinationPath $backupPath -Force -ErrorAction SilentlyContinue
Remove-Item $destinationPath -Force -ErrorAction SilentlyContinue
New-Item -ItemType SymbolicLink -Path $destinationPath -Target $($_.FullName) -Force -ErrorAction SilentlyContinue | Out-Null
$script:setupSummary.Updated += $destinationPath
Write-ColorText "{Blue}[symlink] {Green}(created) {Green}$($_.FullName) {Yellow}--> {Gray}$destinationPath"
} else {
$script:setupSummary.Skipped += "$destinationPath (exists as regular file, use -Force to replace)"
Write-ColorText "{Yellow}[symlink] {Gray}Skipped $destinationPath (exists, use -Force to replace)"
}
}
} else {
# Destination doesn't exist, create symlink
New-Item -ItemType SymbolicLink -Path $destinationPath -Target $($_.FullName) -Force -ErrorAction SilentlyContinue | Out-Null
$script:setupSummary.Created += $destinationPath
Write-ColorText "{Blue}[symlink] {Green}(created) {Green}$($_.FullName) {Yellow}--> {Gray}$destinationPath"
}
}
}
function Copy-ConfigFiles {
param (
[string]$Source,
[string]$Destination,
[switch]$Recurse
)
if (!(Test-Path $Source)) {
Write-ColorText "{Yellow}[copy] {Gray}Source path does not exist: $Source"
$script:setupSummary.Skipped += "Copy from $Source (source not found)"
return
}
# Get all items (files and directories) from source
Get-ChildItem $Source -Recurse:$Recurse | ForEach-Object {
$destinationPath = $_.FullName -replace [regex]::Escape($Source), $Destination
$destinationDir = Split-Path $destinationPath
# Create destination directory if it doesn't exist
if (!(Test-Path $destinationDir)) {
New-Item $destinationDir -ItemType Directory -Force -ErrorAction SilentlyContinue | Out-Null
}
if ($_.PSIsContainer) {
# For directories, ensure they exist
if (!(Test-Path $destinationPath)) {
New-Item $destinationPath -ItemType Directory -Force -ErrorAction SilentlyContinue | Out-Null
$script:setupSummary.Created += "$destinationPath\"
} else {
$script:setupSummary.Exists += "$destinationPath\"
}
} else {
# For files, check if they need to be copied/updated
if (Test-Path $destinationPath) {
# Check if file content differs
$sourceHash = (Get-FileHash $_.FullName -ErrorAction SilentlyContinue).Hash
$destHash = (Get-FileHash $destinationPath -ErrorAction SilentlyContinue).Hash
if ($sourceHash -ne $destHash) {
# Files differ, backup and update
if ($Force) {
$backupPath = "$destinationPath.backup.$(Get-Date -Format 'yyyyMMdd-HHmmss')"
Copy-Item $destinationPath $backupPath -Force -ErrorAction SilentlyContinue
Copy-Item $_.FullName $destinationPath -Force -ErrorAction SilentlyContinue
$script:setupSummary.Updated += $destinationPath
Write-ColorText "{Blue}[copy] {Yellow}(updated) {Green}$($_.FullName) {Yellow}--> {Gray}$destinationPath"
} else {
$script:setupSummary.Skipped += "$destinationPath (exists, use -Force to update)"
Write-ColorText "{Yellow}[copy] {Gray}Skipped $destinationPath (exists, use -Force to update)"
}
} else {
# Files are identical, skip
$script:setupSummary.Exists += $destinationPath
Write-ColorText "{Blue}[copy] {Yellow}(exists) {Gray}$destinationPath"
}
} else {
# Destination doesn't exist, copy file
Copy-Item $_.FullName $destinationPath -Force -ErrorAction SilentlyContinue
$script:setupSummary.Created += $destinationPath
Write-ColorText "{Blue}[copy] {Green}(created) {Green}$($_.FullName) {Yellow}--> {Gray}$destinationPath"
}
}
}
}
########################################################################
### MAIN SCRIPT ###
########################################################################
# if not internet connection, then we will exit this script immediately
$internetConnection = Test-NetConnection google.com -CommonTCPPort HTTP -InformationLevel Detailed -WarningAction SilentlyContinue
$internetAvailable = $internetConnection.TcpTestSucceeded
if ($internetAvailable -eq $False) {
Write-Warning "NO INTERNET CONNECTION AVAILABLE!"
Write-Host "Please check your internet connection and re-run this script.`n"
for ($countdown = 3; $countdown -ge 0; $countdown--) {
Write-ColorText "`r{DarkGray}Automatically exit this script in {Blue}$countdown second(s){DarkGray}..." -NoNewLine
Start-Sleep -Seconds 1
}
exit
}
Write-Progress -Completed; Clear-Host
Write-ColorText "`n✅ {Green}Internet Connection available.`n`n{DarkGray}Start running setup process..."
Start-Sleep -Seconds 3
# set current working directory location
$currentLocation = "$($(Get-Location).Path)"
Set-Location $PSScriptRoot
[System.Environment]::CurrentDirectory = $PSScriptRoot
$i = 1
######################################################################
### NERD FONTS ###
######################################################################
if (Should-RunSection "NerdFonts") {
# install nerd fonts
Write-TitleBox -Title "Nerd Fonts Installation"
if ($Force) {
Write-ColorText "{Yellow}Force mode: Reinstalling Nerd Fonts..."
& ([scriptblock]::Create((Invoke-WebRequest 'https://to.loredo.me/Install-NerdFont.ps1'))) -Scope AllUsers -Confirm:$False
} else {
Write-ColorText "{Green}The following fonts are highly recommended:`n{DarkGray}(Please skip this step if you already installed Nerd Fonts)`n`n {Gray}● Cascadia Code Nerd Font`n ● FantasqueSansM Nerd Font`n ● FiraCode Nerd Font`n ● JetBrainsMono Nerd Font`n"
for ($count = 5; $count -ge 0; $count--) {
Write-ColorText "`r{Magenta}Install Nerd Fonts now? [y/N]: {DarkGray}(Exit in {Blue}$count {DarkGray}seconds) {Gray}" -NoNewLine
if ([System.Console]::KeyAvailable) {
$key = [System.Console]::ReadKey($false)
if ($key.Key -ne 'Y') {
Write-ColorText "`r{DarkGray}Skipped installing Nerd Fonts... "