-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.ps1
More file actions
1774 lines (1639 loc) · 87.5 KB
/
Copy pathsetup.ps1
File metadata and controls
1774 lines (1639 loc) · 87.5 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
### Install PowerShellPerfect tools, fonts, themes, and Windows Terminal settings.
param(
[ValidateRange(0, 100)]
[int]$Opacity = 75,
[string]$ColorScheme,
[ValidateRange(6, 30)]
[int]$FontSize = 11,
# Copy profile assets from a local repository instead of GitHub.
[string]$LocalRepo = '',
[switch]$CiMode,
# Control the interactive setup wizard, defaults, and resumable state.
[switch]$Wizard,
[switch]$SkipWizard,
[switch]$Resume,
[ValidatePattern('^[A-Fa-f0-9]{64}$')]
[string]$ExpectedSha256,
[switch]$SkipHashCheck
)
# Normalize known agent env vars to AI_AGENT (same as profile).
if (-not [bool]$env:AI_AGENT -and ([bool]$env:AGENT_ID -or [bool]$env:CLAUDE_CODE -or [bool]$env:CODEX -or [bool]$env:CODEX_AGENT)) {
$env:AI_AGENT = '1'
}
# Enforce TLS 1.2 for HTTPS requests on Windows PowerShell 5.1.
if ($PSVersionTable.PSVersion.Major -lt 6) {
try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 } catch { $null = $_ }
}
$RepoBase = "https://raw.githubusercontent.com/26zl/PowerShellPerfect/main"
$script:DownloadedProfilePath = $null
$script:DownloadedThemeConfigPath = $null
$script:DownloadedTerminalConfigPath = $null
$script:VerifiedInstallBundle = $false
# Use the adjacent local repository when available and -LocalRepo is omitted.
if ([string]::IsNullOrWhiteSpace($LocalRepo) -and $PSScriptRoot -and
(Test-Path -LiteralPath (Join-Path $PSScriptRoot 'Microsoft.PowerShell_profile.ps1')) -and
(Test-Path -LiteralPath (Join-Path $PSScriptRoot 'theme.json')) -and
(Test-Path -LiteralPath (Join-Path $PSScriptRoot 'terminal-config.json'))) {
$LocalRepo = $PSScriptRoot
Write-Host "Using local repo checkout: $LocalRepo" -ForegroundColor DarkGray
}
function Get-CombinedSha256 {
param([Parameter(Mandatory)][string[]]$Parts)
$sha = [System.Security.Cryptography.SHA256]::Create()
try {
return [BitConverter]::ToString(
$sha.ComputeHash([System.Text.Encoding]::UTF8.GetBytes(($Parts -join ':')))
).Replace('-', '')
}
finally { $sha.Dispose() }
}
# Download with retries, size validation, and corrupt-file cleanup.
function Invoke-DownloadWithRetry {
param(
[Parameter(Mandatory)]
[string]$Uri,
[Parameter(Mandatory)]
[string]$OutFile,
[int]$TimeoutSec = 10,
[int]$MaxAttempts = 2,
[int]$BackoffSec = 2
)
for ($attempt = 1; $attempt -le $MaxAttempts; $attempt++) {
try {
Remove-Item $OutFile -Force -ErrorAction SilentlyContinue
Invoke-RestMethod -Uri $Uri -OutFile $OutFile -TimeoutSec $TimeoutSec -UseBasicParsing -ErrorAction Stop
if (-not (Test-Path $OutFile) -or (Get-Item $OutFile).Length -eq 0) {
Remove-Item $OutFile -Force -ErrorAction SilentlyContinue
throw 'Downloaded file is missing or empty'
}
return
}
catch {
if ($attempt -lt $MaxAttempts) {
Write-Host " Download failed (attempt $attempt/$MaxAttempts): $_ Retrying in ${BackoffSec}s..." -ForegroundColor Yellow
Start-Sleep -Seconds $BackoffSec
}
else {
throw $_
}
}
}
}
function Remove-SafeTempDirectory {
param(
[AllowNull()][string]$Path,
[string]$NamePrefix = 'psp-'
)
if ([string]::IsNullOrWhiteSpace($Path)) { return }
$resolved = Resolve-Path -LiteralPath $Path -ErrorAction SilentlyContinue
if (-not $resolved) { return }
$tempBase = [System.IO.Path]::GetFullPath([System.IO.Path]::GetTempPath())
$rootFull = [System.IO.Path]::GetFullPath($resolved.ProviderPath)
$rootName = Split-Path -Path $rootFull -Leaf
if ($rootName -like "$NamePrefix*" -and $rootFull.StartsWith($tempBase, [System.StringComparison]::OrdinalIgnoreCase)) {
Remove-Item -LiteralPath $rootFull -Recurse -Force -ErrorAction SilentlyContinue
}
else {
Write-Host " Skipped temp cleanup outside expected temp root: $rootFull" -ForegroundColor Yellow
}
}
function Initialize-RemoteInstallBundle {
if ($LocalRepo -or $script:VerifiedInstallBundle) { return }
$tempSuffix = [System.IO.Path]::GetRandomFileName()
$bundleProfile = Join-Path $env:TEMP "psp-setup-profile-$tempSuffix.ps1"
$bundleTheme = Join-Path $env:TEMP "psp-setup-theme-$tempSuffix.json"
$bundleTerminal = Join-Path $env:TEMP "psp-setup-terminal-$tempSuffix.json"
try {
Invoke-DownloadWithRetry -Uri "$RepoBase/Microsoft.PowerShell_profile.ps1" -OutFile $bundleProfile -TimeoutSec 30
Invoke-DownloadWithRetry -Uri "$RepoBase/theme.json" -OutFile $bundleTheme
Invoke-DownloadWithRetry -Uri "$RepoBase/terminal-config.json" -OutFile $bundleTerminal
$profileHash = (Get-FileHash -LiteralPath $bundleProfile -Algorithm SHA256).Hash
$themeHash = (Get-FileHash -LiteralPath $bundleTheme -Algorithm SHA256).Hash
$terminalHash = (Get-FileHash -LiteralPath $bundleTerminal -Algorithm SHA256).Hash
$combinedHash = Get-CombinedSha256 -Parts @(
"profile:$profileHash"
"theme:$themeHash"
"terminal:$terminalHash"
)
if (-not $SkipHashCheck) {
if (-not $ExpectedSha256) {
Write-Host "Downloaded install bundle hashes:" -ForegroundColor Yellow
Write-Host " profile.ps1: $profileHash" -ForegroundColor Yellow
Write-Host " theme.json: $themeHash" -ForegroundColor Yellow
Write-Host " terminal-config: $terminalHash" -ForegroundColor Yellow
Write-Host " combined: $combinedHash" -ForegroundColor Yellow
throw "Hash input required. Re-run with -ExpectedSha256 '$combinedHash' or -SkipHashCheck."
}
if ($combinedHash -ne $ExpectedSha256.ToUpperInvariant()) {
throw "Combined hash mismatch. Expected $($ExpectedSha256.ToUpperInvariant()), got $combinedHash."
}
}
$script:DownloadedProfilePath = $bundleProfile
$script:DownloadedThemeConfigPath = $bundleTheme
$script:DownloadedTerminalConfigPath = $bundleTerminal
$script:VerifiedInstallBundle = $true
}
catch {
Remove-Item $bundleProfile, $bundleTheme, $bundleTerminal -Force -ErrorAction SilentlyContinue
throw
}
}
function Test-IsTrustedRawGitHubUrl {
param([Parameter(Mandatory)][string]$Url)
try { $uri = [Uri]$Url } catch { return $false }
if ($uri.Scheme -ne 'https') { return $false }
return $uri.Host -in @('raw.githubusercontent.com', 'githubusercontent.com')
}
function Resolve-SetupSourcePath {
param([Parameter(Mandatory)][ValidateSet('profile', 'theme', 'terminal')][string]$Kind)
if ($LocalRepo) {
switch ($Kind) {
'profile' { return (Join-Path $LocalRepo 'Microsoft.PowerShell_profile.ps1') }
'theme' { return (Join-Path $LocalRepo 'theme.json') }
'terminal' { return (Join-Path $LocalRepo 'terminal-config.json') }
}
}
Initialize-RemoteInstallBundle
switch ($Kind) {
'profile' { return $script:DownloadedProfilePath }
'theme' { return $script:DownloadedThemeConfigPath }
'terminal' { return $script:DownloadedTerminalConfigPath }
}
}
# Define the install wizard's curated Windows Terminal color schemes.
$script:CuratedSchemes = @(
@{ Name = 'Tokyo Night'; Desc = 'Cool blue-purple, balanced for long coding sessions (default)'
Scheme = @{ name = 'Tokyo Night'; background = '#1a1b26'; foreground = '#a9b1d6'; cursorColor = '#a9b1d6'; selectionBackground = '#33467c'
black = '#32344a'; red = '#f7768e'; green = '#9ece6a'; yellow = '#e0af68'; blue = '#7aa2f7'; purple = '#ad8ee6'; cyan = '#449dab'; white = '#787c99'
brightBlack = '#444b6a'; brightRed = '#ff7a93'; brightGreen = '#b9f27c'; brightYellow = '#ff9e64'; brightBlue = '#7da6ff'; brightPurple = '#bb9af7'; brightCyan = '#0db9d7'; brightWhite = '#acb0d0' } }
@{ Name = 'Gruvbox Dark'; Desc = 'Retro warm yellow/orange/red, low-contrast and easy on the eyes'
Scheme = @{ name = 'Gruvbox Dark'; background = '#282828'; foreground = '#ebdbb2'; cursorColor = '#ebdbb2'; selectionBackground = '#665c54'
black = '#282828'; red = '#cc241d'; green = '#98971a'; yellow = '#d79921'; blue = '#458588'; purple = '#b16286'; cyan = '#689d6a'; white = '#a89984'
brightBlack = '#928374'; brightRed = '#fb4934'; brightGreen = '#b8bb26'; brightYellow = '#fabd2f'; brightBlue = '#83a598'; brightPurple = '#d3869b'; brightCyan = '#8ec07c'; brightWhite = '#ebdbb2' } }
@{ Name = 'Dracula'; Desc = 'Dark purple with vibrant pink/green/cyan accents'
Scheme = @{ name = 'Dracula'; background = '#282a36'; foreground = '#f8f8f2'; cursorColor = '#f8f8f2'; selectionBackground = '#44475a'
black = '#21222c'; red = '#ff5555'; green = '#50fa7b'; yellow = '#f1fa8c'; blue = '#bd93f9'; purple = '#ff79c6'; cyan = '#8be9fd'; white = '#f8f8f2'
brightBlack = '#6272a4'; brightRed = '#ff6e6e'; brightGreen = '#69ff94'; brightYellow = '#ffffa5'; brightBlue = '#d6acff'; brightPurple = '#ff92df'; brightCyan = '#a4ffff'; brightWhite = '#ffffff' } }
@{ Name = 'Catppuccin Mocha'; Desc = 'Soft pastel dark; popular with modern dev community'
Scheme = @{ name = 'Catppuccin Mocha'; background = '#1e1e2e'; foreground = '#cdd6f4'; cursorColor = '#f5e0dc'; selectionBackground = '#585b70'
black = '#45475a'; red = '#f38ba8'; green = '#a6e3a1'; yellow = '#f9e2af'; blue = '#89b4fa'; purple = '#f5c2e7'; cyan = '#94e2d5'; white = '#bac2de'
brightBlack = '#585b70'; brightRed = '#f38ba8'; brightGreen = '#a6e3a1'; brightYellow = '#f9e2af'; brightBlue = '#89b4fa'; brightPurple = '#f5c2e7'; brightCyan = '#94e2d5'; brightWhite = '#a6adc8' } }
@{ Name = 'Nord'; Desc = 'Cool arctic blues and frosty whites, minimal contrast'
Scheme = @{ name = 'Nord'; background = '#2e3440'; foreground = '#d8dee9'; cursorColor = '#d8dee9'; selectionBackground = '#4c566a'
black = '#3b4252'; red = '#bf616a'; green = '#a3be8c'; yellow = '#ebcb8b'; blue = '#81a1c1'; purple = '#b48ead'; cyan = '#88c0d0'; white = '#e5e9f0'
brightBlack = '#4c566a'; brightRed = '#bf616a'; brightGreen = '#a3be8c'; brightYellow = '#ebcb8b'; brightBlue = '#81a1c1'; brightPurple = '#b48ead'; brightCyan = '#8fbcbb'; brightWhite = '#eceff4' } }
@{ Name = 'One Half Dark'; Desc = 'Atom-inspired, balanced mid-contrast'
Scheme = @{ name = 'One Half Dark'; background = '#282c34'; foreground = '#dcdfe4'; cursorColor = '#a3b3cc'; selectionBackground = '#474e5d'
black = '#282c34'; red = '#e06c75'; green = '#98c379'; yellow = '#e5c07b'; blue = '#61afef'; purple = '#c678dd'; cyan = '#56b6c2'; white = '#dcdfe4'
brightBlack = '#5d677a'; brightRed = '#e06c75'; brightGreen = '#98c379'; brightYellow = '#e5c07b'; brightBlue = '#61afef'; brightPurple = '#c678dd'; brightCyan = '#56b6c2'; brightWhite = '#dcdfe4' } }
@{ Name = 'Solarized Dark'; Desc = 'Ethan Schoonover classic, low eye strain'
Scheme = @{ name = 'Solarized Dark'; background = '#002b36'; foreground = '#839496'; cursorColor = '#93a1a1'; selectionBackground = '#073642'
black = '#073642'; red = '#dc322f'; green = '#859900'; yellow = '#b58900'; blue = '#268bd2'; purple = '#d33682'; cyan = '#2aa198'; white = '#eee8d5'
brightBlack = '#002b36'; brightRed = '#cb4b16'; brightGreen = '#586e75'; brightYellow = '#657b83'; brightBlue = '#839496'; brightPurple = '#6c71c4'; brightCyan = '#93a1a1'; brightWhite = '#fdf6e3' } }
)
# Map curated Nerd Font release assets to their Windows display names.
$script:CuratedFonts = @(
@{ Asset = 'CascadiaCode'; DisplayName = 'CaskaydiaCove NF'; Desc = 'Microsoft Cascadia + icons (default)' }
@{ Asset = 'JetBrainsMono'; DisplayName = 'JetBrainsMono NF'; Desc = 'JetBrains flagship, tight + readable' }
@{ Asset = 'FiraCode'; DisplayName = 'FiraCode NF'; Desc = 'Popular ligature font' }
@{ Asset = 'Meslo'; DisplayName = 'MesloLGM NF'; Desc = 'p10k default, excellent rendering' }
@{ Asset = 'Hack'; DisplayName = 'Hack NF'; Desc = 'Simple + workhorse' }
@{ Asset = 'Iosevka'; DisplayName = 'Iosevka NF'; Desc = 'Narrow monospace, space-efficient' }
)
# Return one wizard choice from stdin, Out-GridView, or fzf.
function Select-WizardItem {
param(
[Parameter(Mandatory)][string]$Title,
[Parameter(Mandatory)][array]$Items, # array of hashtables with .Name and .Desc
[string]$DefaultName, # pre-selected (Enter to accept)
[switch]$AllowSkip # Enter with no default = skip
)
Write-Host ''
Write-Host ("-- {0} --" -f $Title) -ForegroundColor Cyan
for ($i = 0; $i -lt $Items.Count; $i++) {
$marker = if ($DefaultName -and $Items[$i].Name -eq $DefaultName) { '>' } else { ' ' }
$desc = if ($Items[$i].Desc) { " - $($Items[$i].Desc)" } else { '' }
Write-Host (" {0} [{1,2}] {2}{3}" -f $marker, ($i + 1), $Items[$i].Name, $desc)
}
$defaultHint = if ($DefaultName) { " (Enter = $DefaultName)" } elseif ($AllowSkip) { ' (Enter = skip)' } else { '' }
$prompt = "Pick 1-$($Items.Count)$defaultHint"
do {
$raw = Read-Host $prompt
if ([string]::IsNullOrWhiteSpace($raw)) {
if ($DefaultName) { return $Items | Where-Object { $_.Name -eq $DefaultName } | Select-Object -First 1 }
if ($AllowSkip) { return $null }
continue
}
$n = 0
if ([int]::TryParse($raw, [ref]$n) -and $n -ge 1 -and $n -le $Items.Count) {
return $Items[$n - 1]
}
# Allow fuzzy name match too
$match = $Items | Where-Object { $_.Name -like "*$raw*" } | Select-Object -First 1
if ($match) { return $match }
Write-Host " Invalid; try again." -ForegroundColor Yellow
} while ($true)
}
# Return the latest Nerd Fonts version with configured and hardcoded fallbacks.
function Get-LatestNerdFontVersion {
try {
$rel = Invoke-RestMethod -Uri 'https://api.github.com/repos/ryanoasis/nerd-fonts/releases/latest' `
-TimeoutSec 15 -UseBasicParsing -Headers @{ 'User-Agent' = 'PowerShellPerfect-setup' } -ErrorAction Stop
if ($rel.tag_name -match 'v?(\d+\.\d+\.\d+)') { return $matches[1] }
}
catch { $null = $_ }
return '3.2.1'
}
# Return Oh My Posh theme names and URLs from GitHub or an empty array on failure.
function Get-OmpThemeList {
$apiUrl = 'https://api.github.com/repos/JanDeDobbeleer/oh-my-posh/contents/themes?ref=main'
try {
$resp = Invoke-RestMethod -Uri $apiUrl -TimeoutSec 15 -UseBasicParsing -Headers @{ 'User-Agent' = 'PowerShellPerfect-setup' } -ErrorAction Stop
}
catch { return @() }
$themes = @()
foreach ($item in $resp) {
if ($item.name -like '*.omp.json') {
$baseName = $item.name -replace '\.omp\.json$', ''
$themes += @{ Name = $baseName; Desc = ''; Url = $item.download_url }
}
}
return $themes | Sort-Object { $_.Name }
}
# Merge non-null wizard choices into user-settings.json.
function Save-WizardChoices {
param(
[Parameter(Mandatory)][hashtable]$Choices,
[Parameter(Mandatory)][string]$UserSettingsPath
)
$utf8 = [System.Text.UTF8Encoding]::new($false)
$s = if (Test-Path $UserSettingsPath) {
try { (Get-Content $UserSettingsPath -Raw | ConvertFrom-Json -ErrorAction Stop) }
catch { [PSCustomObject]@{} }
}
else { [PSCustomObject]@{} }
if ($null -eq $s) { $s = [PSCustomObject]@{} }
# theme (OMP)
if ($Choices.Theme) {
$s | Add-Member -NotePropertyName 'theme' -NotePropertyValue ([PSCustomObject]@{ name = $Choices.Theme.Name; url = $Choices.Theme.Url }) -Force
}
# windowsTerminal.colorScheme + scheme (color scheme)
if ($Choices.Scheme) {
if (-not $s.PSObject.Properties['windowsTerminal']) { $s | Add-Member -NotePropertyName 'windowsTerminal' -NotePropertyValue ([PSCustomObject]@{}) -Force }
$s.windowsTerminal | Add-Member -NotePropertyName 'colorScheme' -NotePropertyValue $Choices.Scheme.name -Force
$s.windowsTerminal | Add-Member -NotePropertyName 'scheme' -NotePropertyValue ([PSCustomObject]$Choices.Scheme) -Force
}
# windowsTerminal.theme + themeDefinition (tab-bar + application chrome theme)
if ($Choices.TabBar) {
if (-not $s.PSObject.Properties['windowsTerminal']) { $s | Add-Member -NotePropertyName 'windowsTerminal' -NotePropertyValue ([PSCustomObject]@{}) -Force }
$appTheme = if ($Choices.AppTheme) { $Choices.AppTheme } else { 'dark' }
$td = [PSCustomObject]@{
name = 'PSP.WizardTabs'
tab = [PSCustomObject]@{ background = $Choices.TabBar; unfocusedBackground = $Choices.TabBar }
tabRow = [PSCustomObject]@{ background = $Choices.TabBar; unfocusedBackground = $Choices.TabBar }
window = [PSCustomObject]@{ applicationTheme = $appTheme }
}
$s.windowsTerminal | Add-Member -NotePropertyName 'theme' -NotePropertyValue 'PSP.WizardTabs' -Force
$s.windowsTerminal | Add-Member -NotePropertyName 'themeDefinition' -NotePropertyValue $td -Force
}
# defaults (font + background + terminal appearance)
if ($Choices.Font -or $Choices.Background -or $Choices.Terminal) {
if (-not $s.PSObject.Properties['defaults']) { $s | Add-Member -NotePropertyName 'defaults' -NotePropertyValue ([PSCustomObject]@{}) -Force }
}
if ($Choices.Font) {
$fontObj = if ($s.defaults.PSObject.Properties['font']) { $s.defaults.font } else { [PSCustomObject]@{} }
$fontObj | Add-Member -NotePropertyName 'face' -NotePropertyValue $Choices.Font.DisplayName -Force
$s.defaults | Add-Member -NotePropertyName 'font' -NotePropertyValue $fontObj -Force
}
if ($Choices.Background -and $Choices.Background.Path) {
$s.defaults | Add-Member -NotePropertyName 'backgroundImage' -NotePropertyValue $Choices.Background.Path -Force
$s.defaults | Add-Member -NotePropertyName 'backgroundImageOpacity' -NotePropertyValue $Choices.Background.Opacity -Force
$s.defaults | Add-Member -NotePropertyName 'backgroundImageStretchMode' -NotePropertyValue 'uniformToFill' -Force
$s.defaults | Add-Member -NotePropertyName 'backgroundImageAlignment' -NotePropertyValue 'center' -Force
}
# Store terminal appearance defaults while preserving the selected font face.
if ($Choices.Terminal) {
foreach ($k in $Choices.Terminal.Keys) {
$v = $Choices.Terminal[$k]
if ($k -eq 'fontSize') {
$fontObj = if ($s.defaults.PSObject.Properties['font']) { $s.defaults.font } else { [PSCustomObject]@{} }
$fontObj | Add-Member -NotePropertyName 'size' -NotePropertyValue $v -Force
$s.defaults | Add-Member -NotePropertyName 'font' -NotePropertyValue $fontObj -Force
}
else {
$s.defaults | Add-Member -NotePropertyName $k -NotePropertyValue $v -Force
}
}
}
# features
if ($Choices.Features) {
if (-not $s.PSObject.Properties['features']) { $s | Add-Member -NotePropertyName 'features' -NotePropertyValue ([PSCustomObject]@{}) -Force }
foreach ($k in $Choices.Features.Keys) {
$s.features | Add-Member -NotePropertyName $k -NotePropertyValue $Choices.Features[$k] -Force
}
}
# Derive PSReadLine colors from the selected terminal scheme when requested.
if ($Choices.PSReadLine -eq 'scheme' -and $Choices.Scheme) {
$sc = $Choices.Scheme
$rl = [PSCustomObject]@{
Command = $sc.brightCyan
Parameter = $sc.cyan
Operator = $sc.yellow
Variable = $sc.foreground
String = $sc.green
Number = $sc.brightBlue
Type = $sc.brightGreen
Comment = $sc.brightBlack
Keyword = $sc.purple
Error = $sc.red
}
if (-not $s.PSObject.Properties['psreadline']) { $s | Add-Member -NotePropertyName 'psreadline' -NotePropertyValue ([PSCustomObject]@{}) -Force }
$s.psreadline | Add-Member -NotePropertyName 'colors' -NotePropertyValue $rl -Force
}
$json = $s | ConvertTo-Json -Depth 20
[System.IO.File]::WriteAllText($UserSettingsPath, $json, $utf8)
}
# Return a yes/no choice with Enter mapped to the default.
function Read-WizardYesNo {
param([Parameter(Mandatory)][string]$Prompt, [bool]$Default = $true)
$hint = if ($Default) { '[Y/n]' } else { '[y/N]' }
$raw = Read-Host "$Prompt $hint"
if ([string]::IsNullOrWhiteSpace($raw)) { return $Default }
return ($raw -match '^(?i:y|yes)$')
}
# Return the main wizard choices as a hashtable for Save-WizardChoices.
function Start-InstallWizard {
param([string]$StatePath)
$choices = @{
Theme = $null # @{ Name='atomic'; Url='...' }
Scheme = $null # full scheme hashtable
Font = $null # curated font entry
Features = $null # hashtable
Background = $null # @{ Path='...'; Opacity=0.15 }
TabBar = $null # hex string
AppTheme = $null # 'dark' | 'light' - WT window.applicationTheme
Terminal = $null # ordered hashtable: opacity, fontSize, useAcrylic, cursorShape, padding, scrollbarState, historySize
PSReadLine = $null # 'default' | 'scheme' - scheme derives from chosen color scheme
Editor = $null # cmd name (code, nvim, notepad, ...)
TelemetryOptOut = $null # $true = set POWERSHELL_TELEMETRY_OPTOUT machine-wide
CompletedSteps = @()
}
# Increment the state version whenever the wizard choice schema changes.
$WIZARD_STATE_SCHEMA = 2
# Resume from state file if caller passed one that exists
if ($StatePath -and (Test-Path $StatePath)) {
try {
$prev = Get-Content $StatePath -Raw | ConvertFrom-Json
$prevSchema = if ($prev.PSObject.Properties['schemaVersion']) { [int]$prev.schemaVersion } else { 1 }
if ($prevSchema -ne $WIZARD_STATE_SCHEMA) {
Write-Host ''
Write-Host ("Wizard state schema mismatch (found v{0}, expected v{1}); starting fresh." -f $prevSchema, $WIZARD_STATE_SCHEMA) -ForegroundColor Yellow
Remove-Item $StatePath -Force -ErrorAction SilentlyContinue
}
else {
# Detect concurrent use of the wizard state file.
$otherPid = if ($prev.PSObject.Properties['ownerPid']) { [int]$prev.ownerPid } else { 0 }
$otherAlive = $false
if ($otherPid -gt 0 -and $otherPid -ne $PID) {
try {
$otherProc = Get-Process -Id $otherPid -ErrorAction Stop
if ($otherProc -and $otherProc.ProcessName -match '^(pwsh|powershell)$') { $otherAlive = $true }
}
catch { $otherAlive = $false }
}
if ($otherAlive) {
Write-Host ''
Write-Host ("Another setup.ps1 wizard (PID {0}) appears to be running with this state file." -f $otherPid) -ForegroundColor Yellow
if (-not (Read-WizardYesNo -Prompt ' Take over anyway? (the other run will silently overwrite on its next save)' -Default $false)) {
throw 'WizardCancelled: concurrent wizard detected.'
}
}
Write-Host ''
Write-Host ("Found wizard state from {0}." -f $prev.Timestamp) -ForegroundColor Yellow
if (Read-WizardYesNo -Prompt 'Resume?' -Default $true) {
foreach ($prop in $prev.Choices.PSObject.Properties) {
$choices[$prop.Name] = $prop.Value
}
# Restore ordered hashtables after the JSON round-trip.
foreach ($field in 'Terminal', 'Features') {
if ($choices[$field] -is [System.Management.Automation.PSCustomObject]) {
$ht = [ordered]@{}
foreach ($p in $choices[$field].PSObject.Properties) { $ht[$p.Name] = $p.Value }
$choices[$field] = $ht
}
}
Write-Host ("Resuming from step after: {0}" -f ($choices.CompletedSteps -join ', ')) -ForegroundColor DarkGray
}
else { Remove-Item $StatePath -Force -ErrorAction SilentlyContinue }
}
}
catch {
if ($_.Exception.Message -like 'WizardCancelled*') { throw }
Remove-Item $StatePath -Force -ErrorAction SilentlyContinue
}
}
function Save-State {
if (-not $StatePath) { return }
$snap = @{ schemaVersion = $WIZARD_STATE_SCHEMA; Timestamp = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss'); ownerPid = $PID; Choices = $choices }
$json = $snap | ConvertTo-Json -Depth 20
[System.IO.File]::WriteAllText($StatePath, $json, [System.Text.UTF8Encoding]::new($false))
}
Write-Host ''
Write-Host '=========================================' -ForegroundColor Magenta
Write-Host ' PowerShellPerfect Install Wizard' -ForegroundColor Magenta
Write-Host '=========================================' -ForegroundColor Magenta
Write-Host ' Pick your cosmetics. All 130+ commands and extensibility APIs ship regardless.' -ForegroundColor DarkGray
Write-Host ' Press Enter at any prompt to accept default / skip that step.' -ForegroundColor DarkGray
# STEP 0: Offer the default preset before the full wizard on new runs.
if ($choices.CompletedSteps.Count -eq 0) {
Write-Host ''
Write-Host '-- Quick start --' -ForegroundColor Cyan
Write-Host ' Preset: Tokyo Night scheme, CascadiaCode Nerd Font, VS Code editor,' -ForegroundColor DarkGray
Write-Host ' scheme-derived PSReadLine colors, dark chrome, default features.' -ForegroundColor DarkGray
if (Read-WizardYesNo -Prompt ' Use quick-start defaults and skip the 10 steps?' -Default $false) {
$tokyoNight = $script:CuratedSchemes | Where-Object { $_.Name -eq 'Tokyo Night' } | Select-Object -First 1
$cascadia = $script:CuratedFonts | Where-Object { $_.DisplayName -match 'Cascadia' } | Select-Object -First 1
$choices.Theme = @{ Name = 'atomic'; Url = 'https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/atomic.omp.json' }
if ($tokyoNight) { $choices.Scheme = $tokyoNight.Scheme }
if ($cascadia) { $choices.Font = $cascadia }
$choices.TabBar = if ($tokyoNight) { $tokyoNight.Scheme.background } else { '#1a1b26' }
$choices.AppTheme = 'dark'
$choices.Terminal = $null # keep terminal-config.json defaults
$choices.PSReadLine = 'scheme'
$choices.Background = $null
$choices.Editor = 'code'
$choices.TelemetryOptOut = $false
$choices.Features = [ordered]@{ psfzf = $true; predictions = $true; startupMessage = $true; perDirProfiles = $true; commandOverrides = $false }
$choices.CompletedSteps = @('Theme', 'Scheme', 'Font', 'TabBar', 'Terminal', 'PSReadLine', 'Background', 'Editor', 'Telemetry', 'Features')
Save-State
Write-Host ' Quick-start preset applied. Jumping to summary.' -ForegroundColor Green
}
}
# STEP 1: OMP theme
if ('Theme' -notin $choices.CompletedSteps) {
Write-Host ''
Write-Host '[1/10] Fetching Oh My Posh theme catalog...' -ForegroundColor Cyan
$themes = Get-OmpThemeList
if ($themes.Count -eq 0) {
Write-Host ' (network failed or empty; keeping default "pure")' -ForegroundColor Yellow
$choices.Theme = @{ Name = 'pure'; Url = 'https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/pure.omp.json' }
}
else {
Write-Host (" {0} themes available. Type number, partial name, or Enter for 'pure' default." -f $themes.Count) -ForegroundColor DarkGray
$pick = Select-WizardItem -Title 'Oh My Posh theme' -Items $themes -DefaultName 'pure'
if ($pick) { $choices.Theme = $pick }
}
$choices.CompletedSteps += 'Theme'
Save-State
}
# STEP 2: color scheme
if ('Scheme' -notin $choices.CompletedSteps) {
$pick = Select-WizardItem -Title 'Windows Terminal color scheme' -Items $script:CuratedSchemes -DefaultName 'Tokyo Night'
if ($pick) { $choices.Scheme = $pick.Scheme }
$choices.CompletedSteps += 'Scheme'
Save-State
}
# STEP 3: Nerd Font
if ('Font' -notin $choices.CompletedSteps) {
$pick = Select-WizardItem -Title 'Nerd Font variant' -Items $script:CuratedFonts -DefaultName 'CascadiaCode'
if ($pick) { $choices.Font = $pick }
$choices.CompletedSteps += 'Font'
Save-State
}
# STEP 4: tab-bar color
if ('TabBar' -notin $choices.CompletedSteps) {
Write-Host ''
Write-Host '-- Tab bar color --' -ForegroundColor Cyan
Write-Host ' The strip at the top where tabs live. Default matches chosen color scheme background.'
$schemeBg = if ($choices.Scheme) { $choices.Scheme.background } else { '#1a1b26' }
$tabPresets = @(
@{ Name = "Scheme match ($schemeBg)"; Desc = 'Seamless - tab bar same as terminal background'; Value = $schemeBg }
@{ Name = 'Pure black (#000000)'; Desc = 'Maximum contrast'; Value = '#000000' }
@{ Name = 'Warm brown (#2a221d)'; Desc = 'Muted dark'; Value = '#2a221d' }
@{ Name = 'Custom hex'; Desc = 'Type your own #rrggbb'; Value = 'custom' }
@{ Name = 'Skip'; Desc = 'Leave WT default'; Value = $null }
)
$pick = Select-WizardItem -Title 'Tab bar color' -Items $tabPresets -DefaultName "Scheme match ($schemeBg)"
if ($pick -and $pick.Value -eq 'custom') {
$hex = Read-Host ' Hex (e.g. #1e1e2e)'
if ($hex -match '^#[0-9A-Fa-f]{6}$') { $choices.TabBar = $hex }
}
elseif ($pick -and $pick.Value) { $choices.TabBar = $pick.Value }
# Select dark or light Windows Terminal window chrome.
$wantLight = Read-WizardYesNo -Prompt ' Use light window chrome (title bar, borders)?' -Default $false
$choices.AppTheme = if ($wantLight) { 'light' } else { 'dark' }
$choices.CompletedSteps += 'TabBar'
Save-State
}
# STEP 5: Collect optional terminal appearance overrides.
if ('Terminal' -notin $choices.CompletedSteps) {
Write-Host ''
Write-Host '-- Terminal appearance --' -ForegroundColor Cyan
Write-Host ' Enter to keep current default for each field.' -ForegroundColor DarkGray
$term = [ordered]@{}
$opRaw = Read-Host ' Opacity 1-100 (default 75)'
$opInt = 0
if ($opRaw -and [int]::TryParse($opRaw, [ref]$opInt) -and $opInt -ge 1 -and $opInt -le 100) {
$term['opacity'] = $opInt
}
$acrylicPrompt = Read-WizardYesNo -Prompt ' Use acrylic (translucent blur behind terminal)?' -Default $false
if ($acrylicPrompt) { $term['useAcrylic'] = $true }
$fsRaw = Read-Host ' Font size 8-24 (default 11)'
$fsInt = 0
if ($fsRaw -and [int]::TryParse($fsRaw, [ref]$fsInt) -and $fsInt -ge 8 -and $fsInt -le 24) {
$term['fontSize'] = $fsInt
}
Write-Host ' Cursor shape: 1=bar 2=block 3=vintage 4=emptyBox 5=filledBox 6=doubleUnderscore' -ForegroundColor DarkGray
$csRaw = Read-Host ' Cursor shape (default bar)'
$csMap = @{ '1' = 'bar'; '2' = 'block'; '3' = 'vintage'; '4' = 'emptyBox'; '5' = 'filledBox'; '6' = 'doubleUnderscore' }
if ($csRaw -and $csMap.ContainsKey($csRaw)) { $term['cursorShape'] = $csMap[$csRaw] }
elseif ($csRaw -and ($csMap.Values -contains $csRaw)) { $term['cursorShape'] = $csRaw }
$padRaw = Read-Host ' Cell padding in pixels 0-50 (default 8)'
$padInt = 0
if ($padRaw -and [int]::TryParse($padRaw, [ref]$padInt) -and $padInt -ge 0 -and $padInt -le 50) {
$term['padding'] = "$padInt, $padInt, $padInt, $padInt"
}
Write-Host ' Scrollbar: 1=visible 2=hidden 3=always' -ForegroundColor DarkGray
$sbRaw = Read-Host ' Scrollbar (default visible)'
$sbMap = @{ '1' = 'visible'; '2' = 'hidden'; '3' = 'always' }
if ($sbRaw -and $sbMap.ContainsKey($sbRaw)) { $term['scrollbarState'] = $sbMap[$sbRaw] }
elseif ($sbRaw -and ($sbMap.Values -contains $sbRaw)) { $term['scrollbarState'] = $sbRaw }
$hsRaw = Read-Host ' History size 100-1000000 (default 20000)'
$hsInt = 0
if ($hsRaw -and [int]::TryParse($hsRaw, [ref]$hsInt) -and $hsInt -ge 100 -and $hsInt -le 1000000) {
$term['historySize'] = $hsInt
}
if ($term.Count -gt 0) { $choices.Terminal = $term }
$choices.CompletedSteps += 'Terminal'
Save-State
}
# STEP 6: Keep, derive, or skip PSReadLine syntax colors.
if ('PSReadLine' -notin $choices.CompletedSteps) {
Write-Host ''
Write-Host '-- PSReadLine syntax colors --' -ForegroundColor Cyan
$rlOptions = @(
@{ Name = 'theme.json default'; Desc = 'Keep the shipped palette'; Value = 'default' }
@{ Name = 'Derive from color scheme'; Desc = 'Map scheme ANSI roles to syntax (Command, String, ...)'; Value = 'scheme' }
@{ Name = 'Skip'; Desc = 'No override; edit user-settings.json later'; Value = $null }
)
$pick = Select-WizardItem -Title 'PSReadLine colors' -Items $rlOptions -DefaultName 'theme.json default'
if ($pick -and $pick.Value) { $choices.PSReadLine = $pick.Value }
$choices.CompletedSteps += 'PSReadLine'
Save-State
}
# STEP 7: background image
if ('Background' -notin $choices.CompletedSteps) {
Write-Host ''
Write-Host '-- Background image (optional) --' -ForegroundColor Cyan
if (Read-WizardYesNo -Prompt 'Set a background image?' -Default $false) {
$bgPath = Read-Host ' Path to image (png/jpg/gif)'
if ($bgPath -and (Test-Path -LiteralPath $bgPath)) {
$opRaw = Read-Host ' Opacity 0.05-0.50 (Enter = 0.10)'
$op = 0.10
$tmp = 0.0
if ($opRaw -and [double]::TryParse($opRaw, [ref]$tmp) -and $tmp -ge 0.05 -and $tmp -le 0.50) { $op = $tmp }
$choices.Background = @{ Path = (Resolve-Path $bgPath).ProviderPath; Opacity = $op }
}
else { Write-Host ' (no file found; skipping)' -ForegroundColor Yellow }
}
$choices.CompletedSteps += 'Background'
Save-State
}
# STEP 8: Editor preference
if ('Editor' -notin $choices.CompletedSteps) {
Write-Host ''
Write-Host '-- Preferred editor --' -ForegroundColor Cyan
$choices.Editor = Select-PreferredEditor
$choices.CompletedSteps += 'Editor'
Save-State
}
# STEP 9: Offer telemetry opt-out when it is not already configured.
if ('Telemetry' -notin $choices.CompletedSteps) {
Write-Host ''
Write-Host '-- PowerShell telemetry --' -ForegroundColor Cyan
if ([System.Environment]::GetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', 'Machine')) {
Write-Host ' POWERSHELL_TELEMETRY_OPTOUT is already set. No change.' -ForegroundColor DarkGray
$choices.TelemetryOptOut = $false
}
else {
$choices.TelemetryOptOut = Read-WizardYesNo -Prompt ' Opt out of PowerShell telemetry? Sets POWERSHELL_TELEMETRY_OPTOUT=true machine-wide' -Default $false
}
$choices.CompletedSteps += 'Telemetry'
Save-State
}
# STEP 10: feature toggles
if ('Features' -notin $choices.CompletedSteps) {
Write-Host ''
Write-Host '-- Profile feature toggles --' -ForegroundColor Cyan
$features = [ordered]@{}
$features['psfzf'] = Read-WizardYesNo -Prompt ' PSFzf fuzzy search (Ctrl+R history, Ctrl+T files)?' -Default $true
$features['predictions'] = Read-WizardYesNo -Prompt ' PSReadLine predictions (autocomplete suggestions)?' -Default $true
$features['startupMessage'] = Read-WizardYesNo -Prompt ' Show "Profile loaded in Xms" at startup?' -Default $true
$features['perDirProfiles'] = Read-WizardYesNo -Prompt ' Auto-load .psprc.ps1 on cd into trusted dirs?' -Default $true
$features['commandOverrides'] = Read-WizardYesNo -Prompt ' Allow user-settings.json commandOverrides (JSON -> scriptblock)?' -Default $false
$choices.Features = $features
$choices.CompletedSteps += 'Features'
Save-State
}
# SUMMARY + confirm
Write-Host ''
Write-Host '=========================================' -ForegroundColor Magenta
Write-Host ' Summary of your choices' -ForegroundColor Magenta
Write-Host '=========================================' -ForegroundColor Magenta
Write-Host (" OMP theme: {0}" -f $(if ($choices.Theme) { $choices.Theme.Name } else { '(default)' }))
Write-Host (" Color scheme: {0}" -f $(if ($choices.Scheme) { $choices.Scheme.name } else { '(default)' }))
Write-Host (" Nerd Font: {0}" -f $(if ($choices.Font) { $choices.Font.DisplayName } else { '(default)' }))
Write-Host (" Tab bar: {0}" -f $(if ($choices.TabBar) { "$($choices.TabBar) ($($choices.AppTheme) chrome)" } else { '(WT default)' }))
Write-Host ' Terminal:'
if ($choices.Terminal) {
foreach ($k in $choices.Terminal.Keys) {
Write-Host (" {0,-16} = {1}" -f $k, $choices.Terminal[$k])
}
}
else { Write-Host ' (all defaults)' -ForegroundColor DarkGray }
Write-Host (" PSReadLine: {0}" -f $(if ($choices.PSReadLine) { $choices.PSReadLine } else { '(theme.json default)' }))
Write-Host (" Background: {0}" -f $(if ($choices.Background) { "$($choices.Background.Path) @ $($choices.Background.Opacity)" } else { '(none)' }))
Write-Host (" Editor: {0}" -f $(if ($choices.Editor) { $choices.Editor } else { '(prompted outside wizard)' }))
Write-Host (" Telemetry: {0}" -f $(if ($choices.TelemetryOptOut) { 'opt out' } else { 'keep (no change)' }))
Write-Host ' Features:'
if ($choices.Features) {
foreach ($k in $choices.Features.Keys) {
Write-Host (" {0,-18} = {1}" -f $k, $choices.Features[$k])
}
}
Write-Host ''
if (-not (Read-WizardYesNo -Prompt 'Apply all choices?' -Default $true)) {
Write-Host 'Wizard cancelled. Re-run setup.ps1 -Wizard to start over, or -Resume to continue.' -ForegroundColor Yellow
throw 'WizardCancelled'
}
# Clean up state file on success
if ($StatePath -and (Test-Path $StatePath)) { Remove-Item $StatePath -Force -ErrorAction SilentlyContinue }
return $choices
}
$isElevated = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
$isCiHost = $CiMode -or [bool]$env:GITHUB_ACTIONS -or [bool]$env:CI
# Elevate local installs while allowing non-admin automation to skip privileged steps.
if (-not $isElevated -and -not $isCiHost) {
Write-Host "Please run this script as an Administrator!" -ForegroundColor Red
if ($PSCommandPath) { exit 1 } else { return }
}
elseif (-not $isElevated -and $isCiHost) {
Write-Host "Running setup.ps1 in CI/non-admin mode. Admin-only steps (LocalMachine execution policy, system-wide font install) will be skipped." -ForegroundColor Yellow
}
# For remote installs, verify/download the profile bundle before any local mutation.
if (-not $LocalRepo) {
try {
Initialize-RemoteInstallBundle
}
catch {
Write-Host "Remote install bundle was not applied: $($_.Exception.Message)" -ForegroundColor Red
Write-Host "No local setup changes were made before this verification step." -ForegroundColor Yellow
if ($PSCommandPath) { exit 1 } else { return }
}
}
# Report restrictive execution policies without changing them.
$currentUserPolicy = Get-ExecutionPolicy -Scope CurrentUser
if ($currentUserPolicy -eq 'AllSigned') {
$canPromptPolicy = [Environment]::UserInteractive -and -not [bool]$env:CI -and -not [bool]$env:AI_AGENT
if ($canPromptPolicy) { try { $null = [Console]::KeyAvailable } catch { $canPromptPolicy = $false } }
if ($canPromptPolicy) {
Write-Host "CurrentUser execution policy is 'AllSigned' (stricter than RemoteSigned)." -ForegroundColor Yellow
$reply = Read-Host " Downgrade to RemoteSigned so the profile can load unsigned scripts? [y/N]"
if ($reply -match '^[Yy]') {
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
Write-Host "Execution policy set to RemoteSigned for CurrentUser." -ForegroundColor Green
}
else {
Write-Host " Kept AllSigned. Profile will not load unless all .ps1 files are signed." -ForegroundColor Yellow
}
}
else {
Write-Host " CurrentUser policy is AllSigned. Skipping downgrade prompt (non-interactive)." -ForegroundColor Yellow
}
}
elseif ($currentUserPolicy -in @('Restricted', 'Undefined')) {
Write-Host "CurrentUser execution policy is '$currentUserPolicy'." -ForegroundColor Yellow
Write-Host " If the installed profile is blocked, opt in manually with:" -ForegroundColor DarkYellow
Write-Host " Set-ExecutionPolicy RemoteSigned -Scope CurrentUser" -ForegroundColor DarkYellow
}
# Offer LocalMachine execution policy guidance only in eligible interactive sessions.
if (-not $isCiHost) {
$machinePolicy = Get-ExecutionPolicy -Scope LocalMachine
if ($machinePolicy -in @('Restricted', 'AllSigned', 'Undefined')) {
Write-Host "LocalMachine execution policy is '$machinePolicy'." -ForegroundColor Yellow
Write-Host " setup.ps1 leaves machine-wide policy unchanged. Change it manually only if you intend to affect all users." -ForegroundColor DarkYellow
}
}
# Function to test internet connectivity (HTTPS - works through corporate proxies/firewalls)
function Test-InternetConnection {
try {
$response = Invoke-WebRequest -Uri "https://github.com" -Method Head -TimeoutSec 5 -UseBasicParsing -ErrorAction Stop
return $response.StatusCode -eq 200
}
catch {
Write-Host "Internet connection is required but not available (cannot reach github.com)." -ForegroundColor Red
return $false
}
}
# Function to install Nerd Fonts
function Install-NerdFonts {
param (
[string]$FontName = "CascadiaCode",
[string]$FontDisplayName = "CaskaydiaCove NF",
[string]$Version = "3.2.1"
)
$tempRoot = $null
try {
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$fontCollection = New-Object System.Drawing.Text.InstalledFontCollection
$fontFamilies = $fontCollection.Families.Name
$fontCollection.Dispose()
if ($fontFamilies -notcontains "${FontDisplayName}") {
Write-Host " Installing ${FontDisplayName}..." -ForegroundColor Yellow
$fontZipUrl = "https://github.com/ryanoasis/nerd-fonts/releases/download/v${Version}/${FontName}.zip"
$tempRoot = Join-Path ([System.IO.Path]::GetTempPath()) ("psp-font-" + [System.IO.Path]::GetRandomFileName())
$zipFilePath = Join-Path $tempRoot "${FontName}.zip"
$extractPath = Join-Path $tempRoot "extract"
New-Item -ItemType Directory -Path $extractPath -Force | Out-Null
Invoke-DownloadWithRetry -Uri $fontZipUrl -OutFile $zipFilePath -TimeoutSec 60 -MaxAttempts 2
if (-not (Test-Path $zipFilePath) -or (Get-Item $zipFilePath).Length -eq 0) {
throw "Font download is missing or empty"
}
Expand-Archive -Path $zipFilePath -DestinationPath $extractPath -Force
$destination = (New-Object -ComObject Shell.Application).Namespace(0x14)
$fontFiles = Get-ChildItem -Path $extractPath -Recurse -Filter "*.ttf"
$copied = 0
foreach ($f in $fontFiles) {
if (-not (Test-Path "$env:SystemRoot\Fonts\$($f.Name)")) {
$destination.CopyHere($f.FullName, 0x10)
$copied++
}
}
# CopyHere is async - wait for fonts to arrive before deleting source
$pending = $null
if ($copied -gt 0) {
$timeout = 60; $elapsed = 0
while ($elapsed -lt $timeout) {
$pending = $fontFiles | Where-Object {
-not (Test-Path "$env:SystemRoot\Fonts\$($_.Name)")
}
if (-not $pending) { break }
Start-Sleep -Milliseconds 500
$elapsed += 0.5
}
}
Remove-SafeTempDirectory -Path $tempRoot -NamePrefix 'psp-font-'
$tempRoot = $null
if ($copied -gt 0 -and $pending) {
# Report a partial font installation when files do not appear before timeout.
Write-Host " Font copy timed out: $(@($pending).Count) of $copied file(s) did not install." -ForegroundColor Red
return $false
}
Write-Host " ${FontDisplayName} installed." -ForegroundColor Green
return $true
}
else {
Write-Host " ${FontDisplayName} already installed." -ForegroundColor Green
return $true
}
}
catch {
Remove-SafeTempDirectory -Path $tempRoot -NamePrefix 'psp-font-'
Write-Host " Failed to install ${FontDisplayName}: $_" -ForegroundColor Red
return $false
}
}
# Return all Windows Terminal settings files using the same implementation as the profile.
function Get-WindowsTerminalSettingsPaths {
$candidates = @(
Join-Path $env:LOCALAPPDATA 'Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json'
Join-Path $env:LOCALAPPDATA 'Packages\Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe\LocalState\settings.json'
Join-Path $env:LOCALAPPDATA 'Packages\Microsoft.WindowsTerminalCanary_8wekyb3d8bbwe\LocalState\settings.json'
Join-Path $env:LOCALAPPDATA 'Microsoft\Windows Terminal\settings.json'
)
@($candidates | Where-Object { Test-Path -LiteralPath $_ })
}
# Resolve external command aliases using the same implementation as the profile.
function Get-ExternalCommandPath {
param(
[Parameter(Mandatory)]
[string]$CommandName
)
$cmd = Get-Command $CommandName -ErrorAction SilentlyContinue
if (-not $cmd) { return $null }
if ($cmd.CommandType -eq 'Alias' -and $cmd.Definition -and $cmd.Definition -ne $CommandName) {
return Get-ExternalCommandPath -CommandName $cmd.Definition
}
$pathCandidates = @($cmd.Path, $cmd.Source, $cmd.Definition) |
Where-Object { $_ -and [System.IO.Path]::IsPathRooted([string]$_) } |
Select-Object -Unique
foreach ($pathCandidate in $pathCandidates) {
if (Test-Path -LiteralPath $pathCandidate -PathType Leaf) {
return $pathCandidate
}
}
return $null
}
function Update-SessionPathFromRegistry {
$machinePath = [System.Environment]::GetEnvironmentVariable('PATH', 'Machine')
$userPath = [System.Environment]::GetEnvironmentVariable('PATH', 'User')
$env:PATH = (@($machinePath, $userPath) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) -join ';'
}
# Resolve oh-my-posh executable path (Get-ExternalCommandPath or known install locations)
function Get-OhMyPoshExecutablePath {
$candidatePaths = @(
(Join-Path $env:LOCALAPPDATA 'Programs\oh-my-posh\bin\oh-my-posh.exe'),
(Join-Path $env:LOCALAPPDATA 'Programs\oh-my-posh\oh-my-posh.exe'),
(Join-Path $env:ProgramFiles 'oh-my-posh\bin\oh-my-posh.exe')
)
$pf86 = [System.Environment]::GetEnvironmentVariable('ProgramFiles(x86)', 'Process')
if ($pf86) {
$candidatePaths += (Join-Path $pf86 'oh-my-posh\bin\oh-my-posh.exe')
}
$resolvedPath = Get-ExternalCommandPath -CommandName 'oh-my-posh'
$windowsAppsRoot = Join-Path $env:LOCALAPPDATA 'Microsoft\WindowsApps'
if ($resolvedPath -and $resolvedPath -notlike "$windowsAppsRoot*") {
return $resolvedPath
}
foreach ($candidatePath in ($candidatePaths | Select-Object -Unique)) {
if (-not (Test-Path -LiteralPath $candidatePath)) { continue }
$candidateDir = Split-Path -Path $candidatePath -Parent
$pathEntries = @($env:PATH -split ';' | Where-Object { $_ })
if ($pathEntries -notcontains $candidateDir) {
$env:PATH = (@($candidateDir, $env:PATH) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) -join ';'
}
return $candidatePath
}
return $null
}
# Check for internet connectivity before proceeding (skip when using a local repo or a verified remote bundle)
if (-not $LocalRepo -and -not $script:VerifiedInstallBundle -and -not (Test-InternetConnection)) {
if ($PSCommandPath) { exit 1 } else { return }
}
# JSONC comment-stripping regex.
$_q = [char]34
$jsoncCommentPattern = "(?m)(?<=^([^$_q]*$_q[^$_q]*$_q)*[^$_q]*)\s*//.*`$"
# Download theme.json (single source of truth for theme + WT metadata)
$profileConfig = $null
$configCachePath = Join-Path $env:LOCALAPPDATA "PowerShellProfile"
if (!(Test-Path -Path $configCachePath)) {
New-Item -Path $configCachePath -ItemType "directory" -Force | Out-Null
}
# Run the wizard before downstream installation steps consume user settings.
$canRunWizard = [Environment]::UserInteractive -and -not $isCiHost -and -not [bool]$env:AI_AGENT
$wantWizard = ($Wizard -or $canRunWizard) -and -not $SkipWizard
if ($wantWizard) {
$wizardState = Join-Path $env:TEMP 'psp-wizard-state.json'
if (-not $Resume -and (Test-Path $wizardState)) {
# Remove wizard state older than 24 hours unless resume was requested.
$age = (Get-Date) - (Get-Item $wizardState).LastWriteTime
if ($age.TotalHours -gt 24) { Remove-Item $wizardState -Force -ErrorAction SilentlyContinue }
}
try {
$wizChoices = Start-InstallWizard -StatePath $wizardState
$userSettingsPath = Join-Path $configCachePath 'user-settings.json'
Save-WizardChoices -Choices $wizChoices -UserSettingsPath $userSettingsPath
Write-Host ''
Write-Host 'Wizard choices saved to user-settings.json.' -ForegroundColor Green
# Install the selected Nerd Font and retain the default fallback on failure.
if ($wizChoices.Font) {
$latestVer = Get-LatestNerdFontVersion
Write-Host ("Installing Nerd Font: {0} v{1}..." -f $wizChoices.Font.DisplayName, $latestVer) -ForegroundColor Cyan
$wizardFontOk = Install-NerdFonts -FontName $wizChoices.Font.Asset -FontDisplayName $wizChoices.Font.DisplayName -Version $latestVer
if ($wizardFontOk) {
$script:WizardFontInstalled = $true
}
else {
Write-Host " Wizard font install did not complete; step [4/10] will retry with the default font." -ForegroundColor Yellow
}
}
# Apply the selected Oh My Posh theme URL to the fetched profile configuration.