Repository navigation
Expand file tree
/
Copy pathsetup.ps1
More file actions
1959 lines (1825 loc) · 110 KB
/
Copy pathsetup.ps1
File metadata and controls
1959 lines (1825 loc) · 110 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: profile, tools, fonts, theme, and Windows Terminal settings.
<#
.SYNOPSIS
Install the PowerShellPerfect profile with its tools, Nerd Font, Oh My Posh theme and Windows Terminal settings.
.DESCRIPTION
Downloads Microsoft.PowerShell_profile.ps1, theme.json and terminal-config.json from one commit of
26zl/PowerShellPerfect (or uses a local checkout), verifies them, and only then changes anything.
No administrator rights are needed: the Nerd Font is installed for the current user and the telemetry
opt-out is set for the current user (both machine-wide when the shell is elevated). winget installs
eza, zoxide, fzf, bat and ripgrep and accepts the winget source and package agreements for you. Oh My Posh
is installed as the pinned portable release build (SHA-256 and signer checked), with winget as the fallback.
Each run is logged to %LOCALAPPDATA%\PowerShellProfile\logs\setup-<timestamp>.log. Use -WhatIf to see the
changes without making them, and Uninstall-Profile to revert them.
.PARAMETER Ref
Branch, release tag (vX.Y.Z) or commit to install from. The ref is resolved to a commit so all files come
from the same commit. A release tag is verified against the SHA256SUMS.txt published with the release.
.PARAMETER ExpectedSha256
Combined SHA-256 of the install bundle (profile, theme.json, terminal-config.json), as printed by a previous
run. Setup stops before changing anything when the downloaded bundle does not match.
.PARAMETER SkipHashCheck
Install without verifying the bundle (trust on first use).
.PARAMETER LocalRepo
Install from a local folder instead of downloading. A folder that holds setup.ps1 next to the profile files
is used automatically unless -Ref or -ExpectedSha256 is given. With -ExpectedSha256 the local files are checked.
A git checkout stores .ps1 files with CRLF line endings, so its hash differs from a release's (which covers the
published LF files); a local run prints the hash of the files it installs.
.PARAMETER Wizard
Run the interactive wizard (theme, color scheme, font, editor, features) even when it would be skipped.
.PARAMETER SkipWizard
Do not run the wizard.
.PARAMETER Resume
Resume an interrupted wizard run.
.PARAMETER CiMode
Non-interactive run for CI and tests: no winget, fonts, PowerShell Gallery modules or prompts.
.PARAMETER Opacity
Windows Terminal opacity (0-100) instead of the terminal-config.json default.
.PARAMETER ColorScheme
Windows Terminal color scheme name instead of the theme.json default.
.PARAMETER FontSize
Windows Terminal font size instead of the terminal-config.json default.
.EXAMPLE
& .\setup.ps1 -Ref v1.0.0
Install release v1.0.0; the downloaded files are checked against the release's SHA256SUMS.txt.
.EXAMPLE
& .\setup.ps1 -Ref main -ExpectedSha256 <hash>
Install the main branch pinned to the bundle hash printed by an earlier run.
.EXAMPLE
.\setup.ps1 -WhatIf
Show what setup would change without changing anything.
.NOTES
Exit codes: 0 = the profile is installed (optional tools that were skipped or failed are listed in the summary);
1 = nothing was applied (verification failed, unsupported system) or the profile could not be installed;
2 = the wizard was cancelled, so nothing was installed.
When setup runs as a script block (the README install command) it sets $LASTEXITCODE instead of exiting and
removes the variables it created in the caller's session. Invoke-Expression (irm | iex) is not supported.
#>
[CmdletBinding(SupportsShouldProcess = $true)]
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,
# Branch, tag (vX.Y.Z) or commit to install from.
[ValidatePattern('^(?!.*\.\.)(?!.*//)[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$')]
[string]$Ref = 'main'
)
Set-StrictMode -Version 1.0
$ErrorActionPreference = 'Stop'
# Run as a script block (the README install command), $script: is the caller's scope; the end of this file removes
# the variables setup adds there.
$callerScriptVariables = if ($PSCommandPath) { $null } else { @(Get-Variable -Scope Script -ErrorAction Ignore | ForEach-Object { $_.Name }) }
# 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 = $_ }
}
$script:RepoOwner = '26zl'
$script:RepoName = 'PowerShellPerfect'
# Nerd Fonts release the curated fonts are pinned to; each Sha256 below comes from that release's SHA-256.txt.
$script:NerdFontVersion = '3.5.1'
# Oh My Posh release the wizard's theme catalog and the preset themes come from.
$script:OmpThemesRef = 'v31.8.0'
$script:PinnedOmpThemes = @{
pure = 'E0786DA374967BF4B4D3B107580AC86246C132679C309291F378D73C1E804E5A'
atomic = '30B2794D47C4015BD3B83680D314F9884050493E7E26B638D0CDA4A97442B2AF'
}
$script:BoundParameterNames = @($PSBoundParameters.Keys)
$script:Bundle = $null
$script:WorkDir = $null
$script:SourceCommit = $null
$script:BundleSha256 = $null
$script:WizardFontInstalled = $false
$script:WizardOmpTheme = $null
$script:WizardEditor = $null
$script:WizardTelemetryHandled = $false
$script:TranscriptStarted = $false
$script:ErrorReported = $false
$script:SetupCancelled = $false
$script:IsElevated = $false
try { $script:IsElevated = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) } catch { $null = $_ }
# CI=false or CI=0, which some build tools tell users to set globally, does not count as CI.
$script:IsCiHost = $CiMode -or [bool]$env:GITHUB_ACTIONS -or ([bool]$env:CI -and $env:CI -ne 'false' -and $env:CI -ne '0')
$script:CanPrompt = [Environment]::UserInteractive -and -not $script:IsCiHost -and -not [bool]$env:AI_AGENT
if ($script:CanPrompt) { try { $null = [Console]::KeyAvailable } catch { $script:CanPrompt = $false } }
# Write host output, dropping colors when the NO_COLOR environment variable is set (https://no-color.org).
function Write-PspHost {
[CmdletBinding()]
param(
[Parameter(Position = 0, ValueFromPipeline = $true, ValueFromRemainingArguments = $true)][object[]]$Object,
[System.ConsoleColor]$ForegroundColor,
[System.ConsoleColor]$BackgroundColor,
[switch]$NoNewline,
[object]$Separator
)
process {
$splat = @{}
if ($null -ne $Object) { $splat.Object = $(if ($Object.Count -eq 1) { $Object[0] } else { $Object }) }
if ($NoNewline) { $splat.NoNewline = $true }
if ($PSBoundParameters.ContainsKey('Separator')) { $splat.Separator = $Separator }
if ([string]::IsNullOrEmpty($env:NO_COLOR)) {
if ($PSBoundParameters.ContainsKey('ForegroundColor')) { $splat.ForegroundColor = $ForegroundColor }
if ($PSBoundParameters.ContainsKey('BackgroundColor')) { $splat.BackgroundColor = $BackgroundColor }
}
Write-Host @splat
}
}
# Download helper with retry, 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
)
# The progress display slows large downloads on Windows PowerShell 5.1 a lot; this scope only.
$ProgressPreference = 'SilentlyContinue'
for ($attempt = 1; $attempt -le $MaxAttempts; $attempt++) {
try {
Remove-Item -LiteralPath $OutFile -Force -ErrorAction SilentlyContinue
Invoke-RestMethod -Uri $Uri -OutFile $OutFile -TimeoutSec $TimeoutSec -UseBasicParsing -ErrorAction Stop
if (-not (Test-Path -LiteralPath $OutFile) -or (Get-Item -LiteralPath $OutFile).Length -eq 0) {
Remove-Item -LiteralPath $OutFile -Force -ErrorAction SilentlyContinue
throw 'Downloaded file is missing or empty'
}
return
}
catch {
if ($attempt -lt $MaxAttempts) {
Write-PspHost " Download failed (attempt $attempt/$MaxAttempts): $_ Retrying in ${BackoffSec}s..." -ForegroundColor Yellow
Start-Sleep -Seconds $BackoffSec
}
else {
throw $_
}
}
}
}
# Return the combined SHA-256 that pins a whole install bundle (profile, theme.json, terminal-config.json).
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() }
}
# Resolve a branch, tag or commit to its full commit SHA through the GitHub API ($null when offline or rate-limited).
function Resolve-PspCommitSha {
param(
[Parameter(Mandatory)][string]$Owner,
[Parameter(Mandatory)][string]$Repo,
[Parameter(Mandatory)][string]$Ref,
[int]$TimeoutSec = 10
)
if ($Ref -match '^[0-9a-fA-F]{40}$') { return $Ref.ToLowerInvariant() }
try {
$uri = 'https://api.github.com/repos/{0}/{1}/commits/{2}' -f $Owner, $Repo, [Uri]::EscapeDataString($Ref)
$headers = @{ 'User-Agent' = 'PowerShellPerfect'; Accept = 'application/vnd.github.sha' }
if ($env:GITHUB_TOKEN) { $headers['Authorization'] = "Bearer $env:GITHUB_TOKEN" }
$sha = [string](Invoke-RestMethod -Uri $uri -Headers $headers -TimeoutSec $TimeoutSec -UseBasicParsing -ErrorAction Stop)
if ($sha.Trim() -match '^[0-9a-f]{40}$') { return $sha.Trim() }
}
catch { $null = $_ }
return $null
}
# Return the SHA-256 values a release publishes in SHA256SUMS.txt, keyed by file name ($null when the ref is not a release tag or the file is unavailable).
function Get-PspReleaseChecksums {
param(
[Parameter(Mandatory)][string]$Owner,
[Parameter(Mandatory)][string]$Repo,
[Parameter(Mandatory)][string]$Tag,
[int]$TimeoutSec = 15
)
if ($Tag -notmatch '^v\d+\.\d+\.\d+$') { return $null }
$tmp = Join-Path ([System.IO.Path]::GetTempPath()) ('psp-sums-' + [System.IO.Path]::GetRandomFileName())
try {
$uri = 'https://github.com/{0}/{1}/releases/download/{2}/SHA256SUMS.txt' -f $Owner, $Repo, $Tag
Invoke-RestMethod -Uri $uri -OutFile $tmp -TimeoutSec $TimeoutSec -UseBasicParsing -ErrorAction Stop
$sums = @{}
foreach ($line in [System.IO.File]::ReadAllLines($tmp)) {
if ($line -match '^([0-9A-Fa-f]{64})\s+\*?(\S+)\s*$') { $sums[$Matches[2]] = $Matches[1].ToUpperInvariant() }
}
if ($sums.Count -eq 0) { return $null }
return $sums
}
catch { return $null }
finally { [System.IO.File]::Delete($tmp) }
}
# Run a native command and capture its output; stderr never becomes a terminating error under ErrorActionPreference Stop.
function Invoke-SetupNative {
param([Parameter(Mandatory)][string]$FilePath, [string[]]$ArgumentList = @())
$ErrorActionPreference = 'Continue'
$output = & $FilePath @ArgumentList 2>&1 | Out-String
[PSCustomObject]@{ ExitCode = $LASTEXITCODE; Output = $output }
}
# Delete a temporary folder this script created, only when it has the expected prefix and sits under the temp folder.
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 -WhatIf:$false -Confirm:$false
}
else {
Write-PspHost " Skipped temp cleanup outside expected temp root: $rootFull" -ForegroundColor Yellow
}
}
# Return $true when github.com answers over HTTPS (works through corporate proxies and 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-PspHost 'Internet connection is required but not available (cannot reach github.com).' -ForegroundColor Red
return $false
}
}
# Locate or download the profile, theme.json and terminal-config.json and verify them before anything is changed.
function Initialize-InstallBundle {
$names = [ordered]@{ Profile = 'Microsoft.PowerShell_profile.ps1'; Theme = 'theme.json'; Terminal = 'terminal-config.json' }
$files = @{}
if ($LocalRepo) {
foreach ($key in $names.Keys) {
$candidate = Join-Path $LocalRepo $names[$key]
if (-not (Test-Path -LiteralPath $candidate -PathType Leaf)) { throw "Local repo is missing $($names[$key]): $LocalRepo" }
$files[$key] = (Resolve-Path -LiteralPath $candidate).ProviderPath
}
}
else {
if (-not (Test-InternetConnection)) { throw 'No internet connection.' }
# Resolve the ref once so all three files come from the same commit (the ref itself is used when the API is unreachable).
$script:SourceCommit = Resolve-PspCommitSha -Owner $script:RepoOwner -Repo $script:RepoName -Ref $Ref
$sourceRef = if ($script:SourceCommit) { $script:SourceCommit } else { $Ref }
$script:WorkDir = Join-Path ([System.IO.Path]::GetTempPath()) ('psp-setup-' + [System.IO.Path]::GetRandomFileName())
[void][System.IO.Directory]::CreateDirectory($script:WorkDir)
Write-PspHost "Downloading the install bundle from $($script:RepoOwner)/$($script:RepoName)@$sourceRef" -ForegroundColor DarkGray
foreach ($key in $names.Keys) {
$target = Join-Path $script:WorkDir $names[$key]
$uri = 'https://raw.githubusercontent.com/{0}/{1}/{2}/{3}' -f $script:RepoOwner, $script:RepoName, $sourceRef, $names[$key]
Invoke-DownloadWithRetry -Uri $uri -OutFile $target -TimeoutSec 30
$files[$key] = $target
}
}
$hashes = @{}
foreach ($key in $names.Keys) { $hashes[$key] = (Get-FileHash -LiteralPath $files[$key] -Algorithm SHA256).Hash }
$combined = Get-CombinedSha256 -Parts @("profile:$($hashes.Profile)", "theme:$($hashes.Theme)", "terminal:$($hashes.Terminal)")
$script:BundleSha256 = $combined
if ($SkipHashCheck) {
Write-PspHost 'Install bundle not verified (-SkipHashCheck).' -ForegroundColor Yellow
}
elseif ($ExpectedSha256) {
if ($combined -ne $ExpectedSha256.ToUpperInvariant()) {
# A git checkout converts .ps1 files to CRLF, so a release hash never matches it.
$localHint = if ($LocalRepo) { ' Release hashes cover the published files; a git checkout has CRLF line endings and hashes differently.' } else { '' }
throw "Combined hash mismatch. Expected $($ExpectedSha256.ToUpperInvariant()), got $combined.$localHint"
}
Write-PspHost "Install bundle verified: $combined" -ForegroundColor Green
}
elseif ($LocalRepo -and (Test-Path -LiteralPath (Join-Path $LocalRepo 'SHA256SUMS.txt') -PathType Leaf)) {
# Release files downloaded next to setup.ps1 come with SHA256SUMS.txt, and every bundle file must match it.
$localSums = @{}
foreach ($line in [System.IO.File]::ReadAllLines((Join-Path $LocalRepo 'SHA256SUMS.txt'))) {
if ($line -match '^([0-9a-fA-F]{64})\s+\*?(\S+)$') { $localSums[$Matches[2]] = $Matches[1].ToUpperInvariant() }
}
foreach ($key in $names.Keys) {
if ($localSums[$names[$key]] -ne $hashes[$key]) { throw "$($names[$key]) in $LocalRepo does not match the SHA256SUMS.txt next to it." }
}
Write-PspHost "Install bundle matches the SHA256SUMS.txt in $LocalRepo." -ForegroundColor Green
}
elseif ($LocalRepo) {
Write-PspHost "Installing from local files in $LocalRepo (not hash-checked). Bundle hash of these files: $combined" -ForegroundColor DarkGray
}
else {
# A release tag is checked against the SHA256SUMS.txt published with that release.
$sums = Get-PspReleaseChecksums -Owner $script:RepoOwner -Repo $script:RepoName -Tag $Ref
if ($sums) {
foreach ($key in $names.Keys) {
if ($sums[$names[$key]] -ne $hashes[$key]) { throw "$($names[$key]) does not match the SHA256SUMS.txt of release $Ref." }
}
Write-PspHost "Install bundle matches the SHA256SUMS.txt of release $Ref." -ForegroundColor Green
}
else {
$sourceRef = if ($script:SourceCommit) { $script:SourceCommit } else { $Ref }
Write-PspHost 'Downloaded install bundle hashes:' -ForegroundColor Yellow
Write-PspHost " profile.ps1: $($hashes.Profile)" -ForegroundColor Yellow
Write-PspHost " theme.json: $($hashes.Theme)" -ForegroundColor Yellow
Write-PspHost " terminal-config: $($hashes.Terminal)" -ForegroundColor Yellow
Write-PspHost " combined: $combined" -ForegroundColor Yellow
Write-PspHost 'Release tags (-Ref vX.Y.Z) are verified automatically against the release''s SHA256SUMS.txt.' -ForegroundColor DarkYellow
Write-PspHost "For a branch or commit, check it out-of-band first: https://github.com/$($script:RepoOwner)/$($script:RepoName)/commit/$sourceRef" -ForegroundColor DarkYellow
throw "Hash input required. Re-run with -Ref $sourceRef -ExpectedSha256 '$combined' (or -SkipHashCheck)."
}
}
return [PSCustomObject]$files
}
# Shared helpers are loaded from the verified profile, so setup and the profile run the same code.
$script:SharedFunctionNames = @(
'Get-PspCacheDir', 'ConvertTo-NativeArgumentLine', 'Get-Utf8FileText', 'Write-Utf8FileAtomic', 'ConvertFrom-JsonC', 'Read-JsonFile',
'Get-PspProp', 'Get-PspArray', 'Get-PspPath', 'Test-PspProp', 'Set-PspProp', 'Remove-PspProp', 'Copy-PspObject',
'ConvertTo-PspCanonicalJson', 'Test-PspJsonEqual', 'Get-PspComponentPins', 'Get-PspInstallState', 'Set-PspInstallState',
'Get-ExternalCommandPath', 'Update-SessionPathFromRegistry', 'Get-WindowsTerminalSettingsPaths', 'Merge-JsonObject',
'Read-WtChangeManifest', 'Save-WtChangeManifest', 'Add-WtChangeRecord', 'Set-WtRecordedValue', 'Set-WtRecordedArrayItem',
'Set-WtRecordedKeybinding', 'Set-WtRecordedNoLogo', 'Update-WindowsTerminalSettingsFile', 'Get-OhMyPoshExecutablePath',
'Get-PspUserSettingsTemplate', 'Merge-PspUserSettings', 'Test-PspTrustedThemeUrl', 'Read-UserSettingsForWrite', 'Get-PspShellPath',
'Get-WtProfileList', 'Test-PspProfileFile', 'Get-PspOriginalProfileSource'
)
# Helpers newer than 1.0.0 are loaded when the verified profile defines them, so setup can still install an older release with -Ref.
$script:OptionalSharedFunctionNames = @(
'Find-ProfileExecutable', 'Get-OhMyPoshPortablePath', 'Install-OhMyPoshPortable', 'Remove-WtRetiredKeybinding', 'Restore-WtRecordedKeybinding',
'Get-PspOmpThemeRisk', 'Get-PspExecutableVersion', 'Test-PspOmpVersionSafe'
)
# Return the source text of the shared helper functions defined at the top level of a profile file.
function Get-SharedFunctionDefinitions {
param([Parameter(Mandatory)][string]$ProfilePath, [Parameter(Mandatory)][string[]]$Names, [string[]]$OptionalNames = @())
$tokens = $null
$parseErrors = $null
$ast = [System.Management.Automation.Language.Parser]::ParseFile($ProfilePath, [ref]$tokens, [ref]$parseErrors)
if ($parseErrors -and $parseErrors.Count -gt 0) { throw "The profile has $($parseErrors.Count) parse error(s): $($parseErrors[0].Message)" }
$defined = @{}
foreach ($statement in $ast.EndBlock.Statements) {
if ($statement -is [System.Management.Automation.Language.FunctionDefinitionAst]) { $defined[$statement.Name] = $statement.Extent.Text }
}
$missing = @($Names | Where-Object { -not $defined.ContainsKey($_) })
if ($missing.Count -gt 0) { throw "The profile does not define: $($missing -join ', ')" }
foreach ($name in $Names) { $defined[$name] }
foreach ($name in $OptionalNames) { if ($defined.ContainsKey($name)) { $defined[$name] } }
}
# 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; Name is the menu label Select-WizardItem renders and matches on.
# Sha256 is the hash of <Asset>.zip in Nerd Fonts $script:NerdFontVersion.
$script:CuratedFonts = @(
@{ Name = 'CascadiaCode'; Asset = 'CascadiaCode'; DisplayName = 'CaskaydiaCove NF'; Desc = 'Microsoft Cascadia + icons (default)'; Sha256 = '1298BF92698AFA06185CF1D05E6AE05F2D8A1E8C3CB45DDF4C3035168AB342A1' }
@{ Name = 'JetBrainsMono'; Asset = 'JetBrainsMono'; DisplayName = 'JetBrainsMono NF'; Desc = 'JetBrains flagship, tight + readable'; Sha256 = 'FAB782A66F7D3019DA64F6572DB9FC5D3A4BCB19F9FA13E2D8A62E3693D6396E' }
@{ Name = 'FiraCode'; Asset = 'FiraCode'; DisplayName = 'FiraCode NF'; Desc = 'Popular ligature font'; Sha256 = '239395BAF60C89B2EAF4862B6B09DB0EF95605CD3E8EEF51C00345822A81A665' }
@{ Name = 'Meslo'; Asset = 'Meslo'; DisplayName = 'MesloLGM NF'; Desc = 'p10k default, excellent rendering'; Sha256 = 'FB104893ECD8F57E8AFACBC0A7086B42657120448D056D6093C728A9AFB8E237' }
@{ Name = 'Hack'; Asset = 'Hack'; DisplayName = 'Hack NF'; Desc = 'Simple + workhorse'; Sha256 = 'FA24DA7DE7CEFE7766614D27762570B20453C852FC1D5B657111666DF9A5E449' }
@{ Name = 'Iosevka'; Asset = 'Iosevka'; DisplayName = 'Iosevka NF'; Desc = 'Narrow monospace, space-efficient'; Sha256 = '0512C8561FDCFED03C5CAE130D1C01F279CFAD19467337F9EAB98A2B730ECC50' }
)
# Editor choices and their winget IDs; this must stay above Start-InstallWizard, which uses it.
$EditorCandidates = @(
@{ Cmd = 'code'; Display = 'Visual Studio Code'; WingetId = 'Microsoft.VisualStudioCode' }
@{ Cmd = 'nvim'; Display = 'Neovim'; WingetId = 'Neovim.Neovim' }
@{ Cmd = 'vim'; Display = 'Vim'; WingetId = 'vim.vim' }
@{ Cmd = 'msedit'; Display = 'Microsoft Edit'; WingetId = 'Microsoft.Edit' }
@{ Cmd = 'subl'; Display = 'Sublime Text'; WingetId = 'SublimeHQ.SublimeText.4' }
@{ Cmd = 'notepad++'; Display = 'Notepad++'; WingetId = 'Notepad++.Notepad++' }
@{ Cmd = 'notepad'; Display = 'Notepad (always available)'; WingetId = $null }
)
# Return the raw URL of an Oh My Posh theme at the pinned Oh My Posh release.
function Get-OmpThemeUrl {
param([Parameter(Mandatory)][string]$Name, [string]$Ref = $script:OmpThemesRef)
'https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/{0}/themes/{1}.omp.json' -f $Ref, $Name
}
# Prompt for one wizard choice by number or partial name.
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)
[string]$Note, # explanation line printed under the title
[switch]$AllowSkip # Enter with no default = skip
)
Write-PspHost ''
Write-PspHost ("-- {0} --" -f $Title) -ForegroundColor Cyan
if ($Note) { Write-PspHost $Note }
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-PspHost (" {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 a partial name too; wildcard characters in the reply are matched literally.
$pattern = '*' + [WildcardPattern]::Escape($raw) + '*'
$match = $Items | Where-Object { $_.Name -like $pattern } | Select-Object -First 1
if ($match) { return $match }
Write-PspHost " Invalid; try again." -ForegroundColor Yellow
} while ($true)
}
# Return the Oh My Posh themes of the pinned release; URLs are built from the pinned ref, not taken from the API.
function Get-OmpThemeList {
param([string]$Ref = $script:OmpThemesRef)
$apiUrl = 'https://api.github.com/repos/JanDeDobbeleer/oh-my-posh/contents/themes?ref={0}' -f [Uri]::EscapeDataString($Ref)
try {
$resp = Invoke-RestMethod -Uri $apiUrl -TimeoutSec 15 -UseBasicParsing -Headers @{ 'User-Agent' = 'PowerShellPerfect-setup' } -ErrorAction Stop
}
catch { return @() }
$themes = foreach ($item in @($resp)) {
$itemName = [string](Get-PspProp $item 'name')
if ($itemName -notmatch '^([A-Za-z0-9._-]+)\.omp\.json$') { continue }
$baseName = $Matches[1]
@{ Name = $baseName; Desc = ''; Url = (Get-OmpThemeUrl -Name $baseName -Ref $Ref); Sha256 = $script:PinnedOmpThemes[$baseName] }
}
return @($themes | Sort-Object { $_.Name })
}
# Merge non-null wizard choices into user-settings.json; a file that exists but does not parse is never overwritten.
function Save-WizardChoices {
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[Parameter(Mandatory)][hashtable]$Choices,
[Parameter(Mandatory)][string]$UserSettingsPath
)
# Comments and trailing commas are accepted on both PowerShell editions.
try { $s = Read-UserSettingsForWrite -Path $UserSettingsPath }
catch { throw "user-settings.json could not be read ($($_.Exception.Message)). Fix or move $UserSettingsPath and run the wizard again; nothing was saved." }
# The install steps skip their template when this file already exists, so the wizard adds the header that explains it.
if (-not $s.PSObject.Properties['_comment']) {
$s | Add-Member -NotePropertyName '_comment' -NotePropertyValue 'User overrides for terminal, theme, and profile behavior. Only add keys you want to override.' -Force
}
# theme (OMP)
if ($Choices.Theme) {
$themeObj = [PSCustomObject]@{ name = $Choices.Theme.Name; url = $Choices.Theme.Url }
$themeSha = Get-PspProp $Choices.Theme 'Sha256'
if ($themeSha) { $themeObj | Add-Member -NotePropertyName 'sha256' -NotePropertyValue $themeSha -Force }
$s | Add-Member -NotePropertyName 'theme' -NotePropertyValue $themeObj -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
}
if (-not $PSCmdlet.ShouldProcess($UserSettingsPath, 'Save wizard choices')) { return }
$dir = Split-Path -Parent $UserSettingsPath
if ($dir -and -not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
# The previous file is kept as user-settings.json.bak (its comments are not carried into the rewritten file).
Write-Utf8FileAtomic -Path $UserSettingsPath -Content ($s | ConvertTo-Json -Depth 20) -BackupPath "$UserSettingsPath.bak"
}
# 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)$')
}
# Rebuild resumed wizard choices from the curated lists and range checks, so an edited state file cannot inject values.
function Resolve-WizardState {
param([AllowNull()][object]$Saved)
$steps = @('Theme', 'Scheme', 'Font', 'TabBar', 'Terminal', 'PSReadLine', 'Background', 'Editor', 'Telemetry', 'Features')
$valid = @{
Theme = $null; Scheme = $null; Font = $null; Features = $null; Background = $null; TabBar = $null; AppTheme = $null
Terminal = $null; PSReadLine = $null; Editor = $null; TelemetryOptOut = $null; CompletedSteps = @()
}
$theme = Get-PspProp $Saved 'Theme'
$themeName = [string](Get-PspProp $theme 'Name')
$themeUrl = [string](Get-PspProp $theme 'Url')
if ($themeName -match '^[A-Za-z0-9._-]+$' -and (Test-PspTrustedThemeUrl $themeUrl)) {
$themeSha = [string](Get-PspProp $theme 'Sha256')
$valid.Theme = @{ Name = $themeName; Url = $themeUrl; Sha256 = $(if ($themeSha -match '^[A-Fa-f0-9]{64}$') { $themeSha } else { $null }) }
}
$schemeName = [string](Get-PspProp (Get-PspProp $Saved 'Scheme') 'name')
$curatedScheme = $script:CuratedSchemes | Where-Object { $_.Scheme.name -eq $schemeName } | Select-Object -First 1
if ($curatedScheme) { $valid.Scheme = $curatedScheme.Scheme }
$fontName = [string](Get-PspProp (Get-PspProp $Saved 'Font') 'Name')
$curatedFont = $script:CuratedFonts | Where-Object { $_.Name -eq $fontName } | Select-Object -First 1
if ($curatedFont) { $valid.Font = $curatedFont }
$tabBar = [string](Get-PspProp $Saved 'TabBar')
if ($tabBar -match '^#[0-9A-Fa-f]{6}$') { $valid.TabBar = $tabBar }
$appTheme = [string](Get-PspProp $Saved 'AppTheme')
if ($appTheme -in 'dark', 'light') { $valid.AppTheme = $appTheme }
$terminal = Get-PspProp $Saved 'Terminal'
if ($terminal) {
$term = [ordered]@{}
$intRanges = @{ opacity = @(1, 100); fontSize = @(8, 24); historySize = @(100, 1000000) }
foreach ($key in $intRanges.Keys) {
$n = 0
if ([int]::TryParse([string](Get-PspProp $terminal $key), [ref]$n) -and $n -ge $intRanges[$key][0] -and $n -le $intRanges[$key][1]) { $term[$key] = $n }
}
if ((Get-PspProp $terminal 'useAcrylic') -eq $true) { $term['useAcrylic'] = $true }
$cursor = [string](Get-PspProp $terminal 'cursorShape')
if ($cursor -in 'bar', 'block', 'vintage', 'emptyBox', 'filledBox', 'doubleUnderscore') { $term['cursorShape'] = $cursor }
$padding = [string](Get-PspProp $terminal 'padding')
if ($padding -match '^(\d{1,2}), \1, \1, \1$' -and [int]$Matches[1] -le 50) { $term['padding'] = $padding }
$scrollbar = [string](Get-PspProp $terminal 'scrollbarState')
if ($scrollbar -in 'visible', 'hidden', 'always') { $term['scrollbarState'] = $scrollbar }
if ($term.Count -gt 0) { $valid.Terminal = $term }
}
$readline = [string](Get-PspProp $Saved 'PSReadLine')
if ($readline -in 'default', 'scheme') { $valid.PSReadLine = $readline }
$background = Get-PspProp $Saved 'Background'
$bgPath = [string](Get-PspProp $background 'Path')
$bgOpacity = 0.0
if ($bgPath -and (Test-Path -LiteralPath $bgPath -PathType Leaf) -and [double]::TryParse([string](Get-PspProp $background 'Opacity'), [ref]$bgOpacity) -and $bgOpacity -ge 0.05 -and $bgOpacity -le 0.5) {
$valid.Background = @{ Path = (Resolve-Path -LiteralPath $bgPath).ProviderPath; Opacity = $bgOpacity }
}
$editor = [string](Get-PspProp $Saved 'Editor')
if ($EditorCandidates | Where-Object { $_.Cmd -eq $editor }) { $valid.Editor = $editor }
$telemetry = Get-PspProp $Saved 'TelemetryOptOut'
if ($telemetry -is [bool]) { $valid.TelemetryOptOut = $telemetry }
$features = Get-PspProp $Saved 'Features'
if ($features) {
$known = [ordered]@{}
foreach ($key in 'psfzf', 'predictions', 'startupMessage', 'perDirProfiles', 'commandOverrides') {
$value = Get-PspProp $features $key
if ($value -is [bool]) { $known[$key] = $value }
}
if ($known.Count -gt 0) { $valid.Features = $known }
}
$valid.CompletedSteps = @((Get-PspArray $Saved 'CompletedSteps') | Where-Object { $steps -contains [string]$_ } | ForEach-Object { [string]$_ } | Select-Object -Unique)
# A step whose saved answer was dropped is asked again instead of silently falling back to the default.
$stepOf = @{ Theme = 'Theme'; Scheme = 'Scheme'; Font = 'Font'; TabBar = 'TabBar'; Terminal = 'Terminal'; PSReadLine = 'PSReadLine'; Background = 'Background'; Editor = 'Editor'; TelemetryOptOut = 'Telemetry'; Features = 'Features' }
$rejected = @(foreach ($key in $stepOf.Keys) { if ($null -ne (Get-PspProp $Saved $key) -and $null -eq $valid[$key] -and $valid.CompletedSteps -contains $stepOf[$key]) { $stepOf[$key] } })
if ($rejected.Count -gt 0) {
$valid.CompletedSteps = @($valid.CompletedSteps | Where-Object { $rejected -notcontains $_ })
Write-PspHost (" Saved answers that are no longer valid are asked again: {0}." -f (($rejected | Sort-Object) -join ', ')) -ForegroundColor Yellow
}
return $valid
}
# Interactive editor preference prompt - returns chosen Cmd string
function Select-PreferredEditor {
$defaultChoice = $null
Write-PspHost ""
Write-PspHost " Select your preferred code editor:" -ForegroundColor Cyan
Write-PspHost ""
for ($i = 0; $i -lt $EditorCandidates.Count; $i++) {
$ed = $EditorCandidates[$i]
$num = $i + 1
$installed = [bool](Get-Command $ed.Cmd -ErrorAction Ignore)
if ($installed) {
if ($null -eq $defaultChoice) { $defaultChoice = $i }
Write-PspHost " $num) $($ed.Display) ($($ed.Cmd)) " -NoNewline -ForegroundColor White
Write-PspHost '[installed]' -ForegroundColor Green
}
else {
Write-PspHost " $num) $($ed.Display) ($($ed.Cmd))" -ForegroundColor DarkGray
}
}
if ($null -eq $defaultChoice) { $defaultChoice = 0 }
$defaultNum = $defaultChoice + 1
Write-PspHost ""
$reply = Read-Host " Choice [$defaultNum]"
if ([string]::IsNullOrWhiteSpace($reply)) {
return $EditorCandidates[$defaultChoice].Cmd
}
$parsed = 0
$chosen = $null
if ([int]::TryParse($reply, [ref]$parsed) -and $parsed -ge 1 -and $parsed -le $EditorCandidates.Count) {
$chosen = $EditorCandidates[$parsed - 1]
}
else {
Write-PspHost " Invalid choice, using default." -ForegroundColor Yellow
return $EditorCandidates[$defaultChoice].Cmd
}
if (-not (Get-Command $chosen.Cmd -ErrorAction Ignore)) {
Write-PspHost " '$($chosen.Cmd)' is not installed." -ForegroundColor Yellow
# Yes means Resolve-ConfiguredEditor installs it with winget later in setup.
$question = if ($chosen.WingetId) { ' Install it with winget during setup (this accepts its license)? [y/N]' } else { ' Use it anyway? [y/N]' }
$confirm = Read-Host $question
if ($confirm -notmatch '^[Yy]') {
Write-PspHost " Using default instead." -ForegroundColor Yellow
return $EditorCandidates[$defaultChoice].Cmd
}
}
return $chosen.Cmd
}
# Return the main wizard choices as a hashtable for Save-WizardChoices.
function Start-InstallWizard {
param([string]$StatePath)
$choices = @{
Theme = $null # @{ Name='atomic'; Url='...'; Sha256='...' }
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 (user, or machine-wide when elevated)
CompletedSteps = @()
}
# Increment the state version whenever the wizard choice schema changes.
$WIZARD_STATE_SCHEMA = 3
# Resume from state file if caller passed one that exists
if ($StatePath -and (Test-Path -LiteralPath $StatePath)) {
try {
$prev = Read-JsonFile $StatePath
$prevSchema = if (Test-PspProp $prev 'schemaVersion') { [int]$prev.schemaVersion } else { 1 }
if ($prevSchema -ne $WIZARD_STATE_SCHEMA) {
Write-PspHost ''
Write-PspHost ("Wizard state schema mismatch (found v{0}, expected v{1}); starting fresh." -f $prevSchema, $WIZARD_STATE_SCHEMA) -ForegroundColor Yellow
Remove-Item -LiteralPath $StatePath -Force -ErrorAction SilentlyContinue
}
else {
# Detect concurrent use of the wizard state file.
$otherPid = if (Test-PspProp $prev '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-PspHost ''
Write-PspHost ("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-PspHost ''
Write-PspHost ("Found wizard state from {0}." -f (Get-PspProp $prev 'Timestamp')) -ForegroundColor Yellow
if (Read-WizardYesNo -Prompt 'Resume?' -Default $true) {
$choices = Resolve-WizardState -Saved (Get-PspProp $prev 'Choices')
Write-PspHost ("Resuming from step after: {0}" -f ($choices.CompletedSteps -join ', ')) -ForegroundColor DarkGray
}
else { Remove-Item -LiteralPath $StatePath -Force -ErrorAction SilentlyContinue }
}
}
catch {
if ($_.Exception.Message -like 'WizardCancelled*') { throw }
Remove-Item -LiteralPath $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 }
$stateDir = Split-Path -Parent $StatePath
if ($stateDir -and -not (Test-Path -LiteralPath $stateDir)) { New-Item -ItemType Directory -Path $stateDir -Force | Out-Null }
Write-Utf8FileAtomic -Path $StatePath -Content ($snap | ConvertTo-Json -Depth 20)
}
Write-PspHost ''
Write-PspHost '=========================================' -ForegroundColor Magenta
Write-PspHost ' PowerShellPerfect Install Wizard' -ForegroundColor Magenta
Write-PspHost '=========================================' -ForegroundColor Magenta
Write-PspHost ' Pick your cosmetics. All 145+ commands and extensibility APIs ship regardless.' -ForegroundColor DarkGray
Write-PspHost ' 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-PspHost ''
Write-PspHost '-- Quick start --' -ForegroundColor Cyan
Write-PspHost ' Preset: Tokyo Night scheme, CascadiaCode Nerd Font, your first installed editor,' -ForegroundColor DarkGray
Write-PspHost ' 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 { $_.Asset -eq 'CascadiaCode' } | Select-Object -First 1
$choices.Theme = @{ Name = 'atomic'; Url = (Get-OmpThemeUrl -Name 'atomic'); Sha256 = $script:PinnedOmpThemes['atomic'] }
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
# The first editor that is already installed, so the preset never installs one (Notepad is always there).
$installedEditor = $EditorCandidates | Where-Object { Get-Command $_.Cmd -ErrorAction Ignore } | Select-Object -First 1
$choices.Editor = if ($installedEditor) { $installedEditor.Cmd } else { 'notepad' }
$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-PspHost ' Quick-start preset applied. Jumping to summary.' -ForegroundColor Green
}
}
# STEP 1: OMP theme
if ('Theme' -notin $choices.CompletedSteps) {
Write-PspHost ''
Write-PspHost ("[1/10] Fetching the Oh My Posh {0} theme catalog..." -f $script:OmpThemesRef) -ForegroundColor Cyan
$themes = Get-OmpThemeList
if ($themes.Count -eq 0) {
Write-PspHost ' (network failed or empty; keeping default "pure")' -ForegroundColor Yellow
$choices.Theme = @{ Name = 'pure'; Url = (Get-OmpThemeUrl -Name 'pure'); Sha256 = $script:PinnedOmpThemes['pure'] }
}
else {
Write-PspHost (" {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) {
$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 }
)
$tabNote = ' The strip at the top where tabs live. Default matches chosen color scheme background.'
$pick = Select-WizardItem -Title 'Tab bar color' -Items $tabPresets -DefaultName "Scheme match ($schemeBg)" -Note $tabNote
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-PspHost ''
Write-PspHost '-- Terminal appearance --' -ForegroundColor Cyan
Write-PspHost ' 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-PspHost ' 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-PspHost ' 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) {
$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 syntax colors' -Items $rlOptions -DefaultName 'Derive from color scheme'
if ($pick -and $pick.Value) { $choices.PSReadLine = $pick.Value }
$choices.CompletedSteps += 'PSReadLine'
Save-State
}
# STEP 7: background image