-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMicrosoft.PowerShell_profile.ps1
More file actions
6516 lines (6102 loc) · 302 KB
/
Copy pathMicrosoft.PowerShell_profile.ps1
File metadata and controls
6516 lines (6102 loc) · 302 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
### PowerShell Profile (26zl)
### https://github.com/26zl/PowerShellPerfect
$profileStopwatch = [System.Diagnostics.Stopwatch]::StartNew()
# Normalize known agent/AI env vars to AI_AGENT.
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'
}
# Detect non-interactive environments that should skip network calls and UI setup.
$isInteractive = [Environment]::UserInteractive -and
-not [bool]$env:CI -and
-not [bool]$env:AI_AGENT -and
-not ($host.Name -eq 'Default Host') -and
-not $(try { [Console]::IsOutputRedirected } catch { $false }) -and
-not ([Environment]::GetCommandLineArgs() | Where-Object { $_ -match '(?i)^-NonI' })
# Enforce TLS 1.2 for network commands on Windows PowerShell 5.1.
if ($PSVersionTable.PSVersion.Major -lt 6) {
try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 } catch { $null = $_ }
}
$repo_root = "https://raw.githubusercontent.com/26zl"
$repo_name = "PowerShellPerfect"
# Store caches outside Documents and use the temp directory when LOCALAPPDATA is unavailable.
$localAppData = if ($env:LOCALAPPDATA) { $env:LOCALAPPDATA } else { [System.IO.Path]::GetTempPath() }
$cacheDir = Join-Path $localAppData "PowerShellProfile"
if (-not (Test-Path $cacheDir)) {
# Cache creation is best-effort.
try { New-Item -ItemType Directory -Path $cacheDir -Force -ErrorAction Stop | Out-Null }
catch { Write-Warning "Could not create cache dir '$cacheDir': $($_.Exception.Message)" }
}
# JSONC comment-stripping regex.
$_q = [char]34
$jsoncCommentPattern = "(?m)(?<=^([^$_q]*$_q[^$_q]*$_q)*[^$_q]*)\s*//.*`$"
# Detect administrator status safely across PowerShell editions and platforms.
$isWindowsOS = (-not (Test-Path Variable:\IsWindows)) -or $IsWindows
if ($isWindowsOS) {
try { $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) }
catch { $isAdmin = $false }
}
else { $isAdmin = $false }
# Protect core Windows processes from profile process-killing commands.
$script:ProtectedProcessNames = @('System', 'Idle', 'Registry', 'csrss', 'wininit', 'winlogon', 'services', 'lsass', 'smss', 'svchost', 'dwm')
# Define tool installation, upgrade, cache, and version metadata.
$script:ProfileTools = @(
@{ Name = "Oh My Posh"; Id = "JanDeDobbeleer.OhMyPosh"; Cmd = "oh-my-posh"; Cache = $null; VerCmd = "version"; UpgradeStrategy = "preserve-direct" }
@{ Name = "eza"; Id = "eza-community.eza"; Cmd = "eza"; Cache = $null; VerCmd = "--version"; UpgradeStrategy = "winget" }
@{ Name = "zoxide"; Id = "ajeetdsouza.zoxide"; Cmd = "zoxide"; Cache = "zoxide-init.ps1"; VerCmd = "--version"; UpgradeStrategy = "winget" }
@{ Name = "fzf"; Id = "junegunn.fzf"; Cmd = "fzf"; Cache = $null; VerCmd = "--version"; UpgradeStrategy = "winget" }
@{ Name = "bat"; Id = "sharkdp.bat"; Cmd = "bat"; Cache = $null; VerCmd = "--version"; UpgradeStrategy = "winget" }
@{ Name = "ripgrep"; Id = "BurntSushi.ripgrep.MSVC"; Cmd = "rg"; Cache = $null; VerCmd = "--version"; UpgradeStrategy = "winget" }
)
# Expose hooks, feature toggles, command metadata, and shared state through $PSP.
$script:PSP = @{
Hooks = @{
OnProfileLoad = [System.Collections.Generic.List[scriptblock]]::new()
PrePrompt = [System.Collections.Generic.List[scriptblock]]::new()
OnCd = [System.Collections.Generic.List[scriptblock]]::new()
}
HelpSections = [System.Collections.Generic.List[object]]::new()
Commands = [System.Collections.Generic.List[object]]::new()
Features = @{
psfzf = $true
predictions = $true
startupMessage = $true
perDirProfiles = $true
# transientPrompt collapses the previous prompt on Enter (p10k-style); no-op without a console host + PSReadLine.
transientPrompt = $false
# Require explicit opt-in before compiling commandOverrides strings as scriptblocks.
commandOverrides = $false
# Keep the weekly GitHub update check disabled by default.
updateCheck = $false
}
# Return the collapsed prompt text used by the customizable transient prompt.
TransientPrompt = { "$ " }
TrustedDirs = [System.Collections.Generic.List[string]]::new()
LastPwd = $null
# Store the most recent directories added by Invoke-PromptStage.
PwdHistory = [System.Collections.Generic.List[string]]::new()
PwdHistoryMax = 20
# Prevent cdb navigation from re-adding the consumed directory to PwdHistory.
SuppressPwdHistoryPush = $false
# Store the tab title without context indicators for the PrePrompt hook.
BaseTitle = $null
}
# Run registered hook actions while isolating errors.
function Invoke-ProfileHook {
[CmdletBinding()]
param([Parameter(Mandatory)][ValidateSet('OnProfileLoad', 'PrePrompt', 'OnCd')][string]$EventName)
if (-not $script:PSP -or -not $script:PSP.Hooks.ContainsKey($EventName)) { return }
foreach ($h in $script:PSP.Hooks[$EventName]) {
try { & $h }
catch {
if ($_.Exception -is [System.Management.Automation.PipelineStoppedException]) { throw }
Write-Warning "Hook '$EventName' failed: $($_.Exception.Message)"
}
}
}
# Register a scriptblock to run on a profile lifecycle event (OnProfileLoad | PrePrompt | OnCd).
function Register-ProfileHook {
[CmdletBinding()]
param(
[Parameter(Mandatory)][ValidateSet('OnProfileLoad', 'PrePrompt', 'OnCd')][string]$EventName,
[Parameter(Mandatory)][scriptblock]$Action
)
$script:PSP.Hooks[$EventName].Add($Action)
}
# Add a custom help section from a plugin or profile_user.ps1.
function Register-HelpSection {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$Title,
[Parameter(Mandatory)][string[]]$Lines
)
$script:PSP.HelpSections.Add([PSCustomObject]@{ Title = $Title; Lines = $Lines })
}
# Add a command to the discovery registry consumed by Get-ProfileCommand.
function Register-ProfileCommand {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$Name,
[Parameter(Mandatory)][string]$Category,
[string]$Synopsis = ''
)
$script:PSP.Commands.Add([PSCustomObject]@{ Name = $Name; Category = $Category; Synopsis = $Synopsis })
}
# Run a scriptblock in a job and return $null on timeout or failure.
function Invoke-WithTimeout {
param(
[Parameter(Mandatory)]
[scriptblock]$ScriptBlock,
[int]$TimeoutSec = 15,
[object[]]$ArgumentList = @()
)
$job = $null
try {
$job = Start-Job -ScriptBlock $ScriptBlock -ArgumentList $ArgumentList
$null = Wait-Job $job -Timeout $TimeoutSec
if ($job.State -ne 'Completed') {
if ($job.State -eq 'Running') { Stop-Job $job -ErrorAction SilentlyContinue }
return $null
}
Receive-Job $job
}
catch { return $null }
finally {
if ($job) { Remove-Job $job -Force -ErrorAction SilentlyContinue }
}
}
# 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
)
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 $_
}
}
}
}
# Quote Start-Process arguments that contain whitespace or quotes.
function ConvertTo-NativeArgumentLine {
param([Parameter(Mandatory)][AllowEmptyCollection()][string[]]$ArgumentList)
($ArgumentList | ForEach-Object {
if ($_ -match '[\s"]') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ }
}) -join ' '
}
# Read text as UTF-8 with BOM detection across PowerShell editions.
function Get-Utf8FileText {
param([Parameter(Mandatory)][string]$Path)
[System.IO.File]::ReadAllText($Path)
}
# Write UTF-8 without BOM through a sibling temp file before replacing the target.
function Write-Utf8FileAtomic {
param([Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)][AllowEmptyString()][string]$Content)
$dir = Split-Path -Parent $Path
if (-not $dir) { $dir = '.' }
$tmp = Join-Path $dir ('.psp-tmp-' + [System.IO.Path]::GetRandomFileName())
try {
[System.IO.File]::WriteAllText($tmp, $Content, [System.Text.UTF8Encoding]::new($false))
Move-Item -LiteralPath $tmp -Destination $Path -Force
}
catch {
if (Test-Path -LiteralPath $tmp) { Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue }
throw
}
}
# Return the upstream main SHA from GitHub or $null on failure.
function Get-LatestMainCommitSha {
try {
$owner = ($repo_root -replace '^https?://(raw\.)?githubusercontent\.com/', '').Trim('/')
$resp = Invoke-RestMethod -Uri "https://api.github.com/repos/$owner/$repo_name/commits/main" -TimeoutSec 3 -UseBasicParsing -ErrorAction Stop
if ($resp -and $resp.sha) { return $resp.sha }
}
catch { $null = $_ }
return $null
}
# Get the full path to an external command
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 ';'
}
# Manage restorable tab titles for long-running commands.
function Push-TabTitle {
param([Parameter(Mandatory)][string]$Title)
$old = $null
try { $old = $Host.UI.RawUI.WindowTitle } catch { $null = $_ }
try { $Host.UI.RawUI.WindowTitle = $Title } catch { $null = $_ }
return $old
}
function Pop-TabTitle {
param([AllowNull()][string]$OldTitle)
if ($null -eq $OldTitle) { return }
try { $Host.UI.RawUI.WindowTitle = $OldTitle } catch { $null = $_ }
}
# Return the first Windows Terminal settings file found across supported install variants (or $null).
function Get-WindowsTerminalSettingsPath {
@(Get-WindowsTerminalSettingsPaths)[0]
}
# Return all Windows Terminal settings files found across supported install variants.
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 $_ })
}
# Merge PSCustomObject overrides recursively so nested user/theme/terminal keys are preserved.
function Merge-JsonObject {
param(
$base,
$override
)
if ($null -eq $override) { return }
if ($null -eq $base) { throw 'Merge-JsonObject: $base cannot be null (caller must pass an object to merge into).' }
foreach ($prop in $override.PSObject.Properties) {
$baseVal = $base.PSObject.Properties[$prop.Name]
if ($baseVal -and $baseVal.Value -is [PSCustomObject] -and $prop.Value -is [PSCustomObject]) {
Merge-JsonObject $baseVal.Value $prop.Value
}
else {
$base | Add-Member -NotePropertyName $prop.Name -NotePropertyValue $prop.Value -Force
}
}
}
# Specific helper to get the path to oh-my-posh executable for cache clearing (since it has a built-in cache clear command instead of a file-based cache)
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
}
# Return OMP install path and kind (windowsapps vs direct) for upgrade logic
function Get-OhMyPoshInstallInfo {
$path = Get-OhMyPoshExecutablePath
if (-not $path) {
return [PSCustomObject]@{
Path = $null
InstallKind = 'missing'
}
}
$windowsAppsRoot = Join-Path $env:LOCALAPPDATA 'Microsoft\WindowsApps'
$installKind = if ($path -like "$windowsAppsRoot*") { 'windowsapps' } else { 'direct' }
return [PSCustomObject]@{
Path = $path
InstallKind = $installKind
}
}
function Test-WingetPackageInstalled {
param(
[Parameter(Mandatory)]
[string]$Id
)
$wingetPath = Get-ExternalCommandPath -CommandName 'winget'
if (-not $wingetPath) { return $false }
try {
$wingetOutput = @(& $wingetPath list --id $Id --exact 2>&1)
$wingetText = (@($wingetOutput) -join [Environment]::NewLine).Trim()
if ($LASTEXITCODE -ne 0 -or -not $wingetText) { return $false }
if ($wingetText -match 'No installed package found') { return $false }
return $wingetText -match [regex]::Escape($Id)
}
catch {
return $false
}
}
function Get-OhMyPoshMsiProductCode {
$roots = @(
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*',
'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*',
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*'
)
$entries = Get-ItemProperty -Path $roots -ErrorAction SilentlyContinue |
Where-Object { $_.DisplayName -eq 'Oh My Posh' }
foreach ($entry in $entries) {
foreach ($uninstallString in @($entry.QuietUninstallString, $entry.UninstallString)) {
if ($uninstallString -and $uninstallString -match '\{[0-9A-Fa-f\-]{36}\}') {
return $Matches[0]
}
}
}
return $null
}
# Resolve executable path for a profile tool (OMP uses Get-OhMyPoshInstallInfo, others use Get-Command)
function Get-ProfileToolExecutablePath {
param(
[Parameter(Mandatory)]
[hashtable]$Tool
)
if ($Tool.Cmd -eq 'oh-my-posh') {
return (Get-OhMyPoshInstallInfo).Path
}
return Get-ExternalCommandPath -CommandName $Tool.Cmd
}
# Get version string for a profile tool by running its VerCmd
function Get-ProfileToolVersionText {
param(
[Parameter(Mandatory)]
[hashtable]$Tool,
[Parameter(Mandatory)]
[string]$ExecutablePath
)
$versionArgs = @()
if ($Tool.VerCmd -is [System.Array]) {
$versionArgs = @($Tool.VerCmd)
}
elseif (-not [string]::IsNullOrWhiteSpace([string]$Tool.VerCmd)) {
$versionArgs = @([string]$Tool.VerCmd)
}
try {
$versionLine = & $ExecutablePath @versionArgs 2>$null |
Where-Object { $_ -match '\d+\.\d+' } |
Select-Object -First 1
if ($versionLine) {
return $versionLine.Trim()
}
}
catch {
return $null
}
return $null
}
# Invoke oh-my-posh with explicit arguments and UTF-8 streams.
function Invoke-OhMyPoshCommand {
param(
[Parameter(Mandatory)]
[string]$ExecutablePath,
[Parameter(Mandatory)]
[string[]]$Arguments
)
$process = New-Object System.Diagnostics.Process
$startInfo = $process.StartInfo
$startInfo.FileName = $ExecutablePath
if ($startInfo.PSObject.Properties.Match('ArgumentList').Count -gt 0) {
$Arguments | ForEach-Object { $null = $startInfo.ArgumentList.Add($_) }
}
else {
$escapedArgs = $Arguments | ForEach-Object {
$s = $_ -replace '(\\+)"', '$1$1"'
$s = $s -replace '(\\+)$', '$1$1'
$s = $s -replace '"', '\"'
"`"$s`""
}
$startInfo.Arguments = $escapedArgs -join ' '
}
$startInfo.StandardErrorEncoding = [System.Text.Encoding]::UTF8
$startInfo.StandardOutputEncoding = [System.Text.Encoding]::UTF8
$startInfo.RedirectStandardError = $true
$startInfo.RedirectStandardOutput = $true
$startInfo.UseShellExecute = $false
$startInfo.CreateNoWindow = $true
if ($PWD.Provider.Name -eq 'FileSystem') {
try {
if (Test-Path -LiteralPath $PWD.ProviderPath) {
$startInfo.WorkingDirectory = $PWD.ProviderPath
}
}
catch {
Write-Verbose "Failed to set oh-my-posh working directory: $_"
}
}
[void]$process.Start()
try {
$stdoutTask = $process.StandardOutput.ReadToEndAsync()
$stderrTask = $process.StandardError.ReadToEndAsync()
$process.WaitForExit()
$stderr = $stderrTask.Result.Trim()
if ($stderr) {
$Host.UI.WriteErrorLine($stderr)
}
return $stdoutTask.Result
}
finally {
$process.Dispose()
}
}
# Gather context for oh-my-posh prompt rendering.
function Get-OhMyPoshPromptContext {
param(
[bool]$OriginalSuccess,
[AllowNull()]
[object]$OriginalLastExitCode
)
$context = [ordered]@{
NoExitCode = $true
ErrorCode = 0
ExecutionTime = 0
StackCount = 0
NonFSWD = $null
TerminalWidth = 0
}
try {
$locations = Get-Location -Stack
if ($locations) {
$context.StackCount = $locations.Count
}
}
catch {
$context.StackCount = 0
}
try {
if ($PWD.Provider.Name -ne 'FileSystem') {
$context.NonFSWD = $PWD.ToString()
}
}
catch {
$context.NonFSWD = $null
}
try {
$terminalWidth = $Host.UI.RawUI.WindowSize.Width
if ($terminalWidth) {
$context.TerminalWidth = $terminalWidth
}
}
catch {
$context.TerminalWidth = 0
}
$lastHistory = Get-History -ErrorAction Ignore -Count 1
if (($null -eq $lastHistory) -or ($script:OhMyPoshLastHistoryId -eq $lastHistory.Id)) {
return [PSCustomObject]$context
}
$script:OhMyPoshLastHistoryId = $lastHistory.Id
$context.NoExitCode = $false
try {
$context.ExecutionTime = [math]::Max(0, [int](($lastHistory.EndExecutionTime - $lastHistory.StartExecutionTime).TotalMilliseconds))
}
catch {
$context.ExecutionTime = 0
}
if ($OriginalSuccess) {
return [PSCustomObject]$context
}
$invocationInfo = $null
try {
$invocationInfo = $global:Error |
Where-Object { $_.GetType().Name -eq 'ErrorRecord' } |
Select-Object -First 1 -ExpandProperty InvocationInfo
}
catch {
$invocationInfo = $null
}
if ($null -ne $invocationInfo -and $invocationInfo.HistoryId -eq $lastHistory.Id) {
$context.ErrorCode = 1
return [PSCustomObject]$context
}
if ($OriginalLastExitCode -is [int] -and $OriginalLastExitCode -ne 0) {
$context.ErrorCode = $OriginalLastExitCode
return [PSCustomObject]$context
}
$context.ErrorCode = 1
return [PSCustomObject]$context
}
# Get prompt text from oh-my-posh with explicit arguments and context.
function Get-OhMyPoshPromptText {
param(
[Parameter(Mandatory)]
[ValidateSet('primary', 'secondary')]
[string]$Type,
[Parameter(Mandatory)]
[string]$ExecutablePath,
[Parameter(Mandatory)]
[string]$ConfigPath,
[bool]$OriginalSuccess = $true,
[AllowNull()]
[object]$OriginalLastExitCode = 0
)
if (-not (Test-Path -LiteralPath $ConfigPath)) {
throw "oh-my-posh config not found: $ConfigPath"
}
$arguments = @(
'print'
$Type
'--config'
$ConfigPath
'--shell=pwsh'
"--shell-version=$($PSVersionTable.PSVersion.ToString())"
)
if ($Type -eq 'primary') {
$context = Get-OhMyPoshPromptContext -OriginalSuccess:$OriginalSuccess -OriginalLastExitCode $OriginalLastExitCode
$arguments += @(
"--status=$($context.ErrorCode)"
"--no-status=$($context.NoExitCode)"
"--execution-time=$($context.ExecutionTime)"
"--stack-count=$($context.StackCount)"
"--terminal-width=$($context.TerminalWidth)"
'--job-count=0'
)
if ($context.NonFSWD) {
$arguments += "--pswd=$($context.NonFSWD)"
}
}
return Invoke-OhMyPoshCommand -ExecutablePath $ExecutablePath -Arguments $arguments
}
# Clear current and legacy oh-my-posh caches.
function Clear-OhMyPoshCaches {
param(
[switch]$Quiet
)
$docRoot = [Environment]::GetFolderPath('MyDocuments')
$legacyCachePaths = @(
(Join-Path $env:LOCALAPPDATA 'PowerShellProfile\omp-init.ps1')
(Join-Path $docRoot 'PowerShell\omp-init.ps1')
(Join-Path $docRoot 'WindowsPowerShell\omp-init.ps1')
) | Select-Object -Unique
foreach ($legacyPath in $legacyCachePaths) {
if (-not (Test-Path $legacyPath)) { continue }
try {
$firstLine = Get-Content $legacyPath -TotalCount 1 -ErrorAction Stop
if ($firstLine -match '^# OMP_CACHE') {
Remove-Item $legacyPath -Force -ErrorAction SilentlyContinue
if (-not $Quiet) {
Write-Host " Removed legacy OMP init cache: $legacyPath" -ForegroundColor DarkGray
}
}
}
catch {
if (-not $Quiet) {
Write-Verbose "Failed to inspect/remove legacy OMP init cache '$legacyPath': $_"
}
}
}
$ompExecutablePath = Get-OhMyPoshExecutablePath
if ($ompExecutablePath) {
try {
& $ompExecutablePath cache clear | Out-Null
if ($LASTEXITCODE -ne 0 -and -not $Quiet) {
Write-Warning "oh-my-posh cache clear exited with code $LASTEXITCODE."
}
}
catch {
if (-not $Quiet) {
Write-Warning "Failed to clear oh-my-posh cache: $_"
}
}
}
}
# Check for Profile Updates (manual only)
function Update-Profile {
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
param(
[ValidatePattern('^[A-Fa-f0-9]{64}$')]
[string]$ExpectedSha256,
[switch]$SkipHashCheck,
[switch]$Force
)
# Use randomized temporary names to avoid concurrent file collisions.
$tempSuffix = [System.IO.Path]::GetRandomFileName()
$tempProfile = Join-Path $env:TEMP "psp-profile-$tempSuffix.ps1"
$tempConfig = Join-Path $env:TEMP "psp-theme-$tempSuffix.json"
$tempTerminalConfig = Join-Path $env:TEMP "psp-terminal-$tempSuffix.json"
$userSettingsPath = Join-Path $cacheDir "user-settings.json"
$userSettingsStatePath = Join-Path $cacheDir "user-settings.applied.sha256"
$phaseErrors = @()
$profileActuallyUpdated = $false
$userSettingsHash = $null
$userSettingsChanged = $false
$userSettingsParsed = $false
$userThemeOverridePresent = $false
$userWindowsTerminalOverridePresent = $false
$userTerminalDefaultsOverridePresent = $false
$userKeybindingsOverridePresent = $false
# Gate downloads behind ShouldProcess so -WhatIf remains offline.
$updateSource = "$repo_root/$repo_name/main"
if (-not $PSCmdlet.ShouldProcess($updateSource, 'Download profile/theme/terminal-config and apply updates')) { return }
try {
# Phase 1: Download profile and config
$profileUrl = "$repo_root/$repo_name/main/Microsoft.PowerShell_profile.ps1"
Invoke-DownloadWithRetry -Uri $profileUrl -OutFile $tempProfile
$configUrl = "$repo_root/$repo_name/main/theme.json"
$configDownloaded = $false
try {
Invoke-DownloadWithRetry -Uri $configUrl -OutFile $tempConfig
$configDownloaded = $true
}
catch {
Write-Warning "Could not download theme.json (non-fatal): $_"
$phaseErrors += "theme.json download: $_"
}
$terminalConfigUrl = "$repo_root/$repo_name/main/terminal-config.json"
$terminalConfigDownloaded = $false
try {
Invoke-DownloadWithRetry -Uri $terminalConfigUrl -OutFile $tempTerminalConfig
$terminalConfigDownloaded = $true
}
catch {
Write-Warning "Could not download terminal-config.json (non-fatal): $_"
$phaseErrors += "terminal-config.json download: $_"
}
# Phase 2: Verify profile hashes in both PowerShell edition directories.
$newHash = (Get-FileHash -Path $tempProfile -Algorithm SHA256).Hash
$_docsRoot = Split-Path (Split-Path $PROFILE)
$_editionDirs = @(
(Join-Path $_docsRoot 'PowerShell')
(Join-Path $_docsRoot 'WindowsPowerShell')
)
$_installedProfiles = foreach ($_ed in $_editionDirs) {
$_p = Join-Path $_ed 'Microsoft.PowerShell_profile.ps1'
if (Test-Path $_p) { $_p }
}
$profileChanged = $false
if (-not $_installedProfiles) {
# Fresh install scenario - always copy
$profileChanged = $true
}
else {
foreach ($_ip in $_installedProfiles) {
if ((Get-FileHash -Path $_ip -Algorithm SHA256).Hash -ne $newHash) {
$profileChanged = $true
break
}
}
}
# Check if config actually changed
$configChanged = $false
$cachedConfig = Join-Path $cacheDir "theme.json"
if ($configDownloaded) {
$newConfigHash = (Get-FileHash -Path $tempConfig -Algorithm SHA256).Hash
$oldConfigHash = if (Test-Path $cachedConfig) { (Get-FileHash -Path $cachedConfig -Algorithm SHA256).Hash } else { "" }
$configChanged = $newConfigHash -ne $oldConfigHash
}
# Check if terminal config actually changed
$terminalConfigChanged = $false
$cachedTerminalConfig = Join-Path $cacheDir "terminal-config.json"
if ($terminalConfigDownloaded) {
$newTerminalConfigHash = (Get-FileHash -Path $tempTerminalConfig -Algorithm SHA256).Hash
$oldTerminalConfigHash = if (Test-Path $cachedTerminalConfig) { (Get-FileHash -Path $cachedTerminalConfig -Algorithm SHA256).Hash } else { "" }
$terminalConfigChanged = $newTerminalConfigHash -ne $oldTerminalConfigHash
}
if (Test-Path $userSettingsPath) {
try {
$userSettingsHash = (Get-FileHash -Path $userSettingsPath -Algorithm SHA256).Hash
$appliedUserSettingsHash = if (Test-Path $userSettingsStatePath) {
(Get-Content $userSettingsStatePath -Raw -ErrorAction Stop).Trim()
}
else {
""
}
$userSettingsChanged = $userSettingsHash -ne $appliedUserSettingsHash
}
catch {
Write-Warning "Could not fingerprint user-settings.json: $_"
$phaseErrors += "user-settings fingerprint: $_"
$userSettingsChanged = $true
}
}
if (-not $profileChanged -and -not $configChanged -and -not $terminalConfigChanged -and -not $userSettingsChanged -and -not $Force) {
Write-Host "Profile is up to date." -ForegroundColor Green
return
}
# Combined hash verification - covers profile + config files (skipped when nothing changed upstream)
if (-not $SkipHashCheck -and ($profileChanged -or $configChanged -or $terminalConfigChanged)) {
$profileLabel = $newHash
$configLabel = if ($configDownloaded) { $newConfigHash } else { "NONE" }
$terminalLabel = if ($terminalConfigDownloaded) { $newTerminalConfigHash } else { "NONE" }
$combinedInput = "profile:${profileLabel}:theme:${configLabel}:terminal:${terminalLabel}"
$sha = [System.Security.Cryptography.SHA256]::Create()
try {
$combinedHash = [BitConverter]::ToString(
$sha.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($combinedInput))
).Replace('-', '')
}
finally { $sha.Dispose() }
if (-not $ExpectedSha256) {
Write-Host "Downloaded file hashes (computed over what was just fetched):" -ForegroundColor Yellow
Write-Host " profile.ps1: $newHash" -ForegroundColor Yellow
if ($configDownloaded) {
Write-Host " theme.json: $newConfigHash" -ForegroundColor Yellow
}
else {
Write-Host " theme.json: (not downloaded)" -ForegroundColor Yellow
}
if ($terminalConfigDownloaded) {
Write-Host " terminal-config: $newTerminalConfigHash" -ForegroundColor Yellow
}
else {
Write-Host " terminal-config: (not downloaded)" -ForegroundColor Yellow
}
Write-Host " combined: $combinedHash" -ForegroundColor Yellow
Write-Host "These hashes confirm FILE INTEGRITY of the current download (no truncation, no corruption)." -ForegroundColor DarkYellow
Write-Host "To pin against a specific upstream commit, verify the SHA out-of-band first:" -ForegroundColor DarkYellow
Write-Host " https://github.com/26zl/PowerShellPerfect/commits/main" -ForegroundColor DarkYellow
throw "Hash input required. Re-run with -ExpectedSha256 '$combinedHash' (reproducible install) or -SkipHashCheck."
}
$expected = $ExpectedSha256.ToUpperInvariant()
if ($combinedHash -ne $expected) {
throw "Combined hash mismatch. Expected $expected, got $combinedHash."
}
}
# Phase 3: Copy changed profiles to existing edition directories and create only the current edition directory.
if ($profileChanged) {
if ($PSCmdlet.ShouldProcess($PROFILE, "Replace profile with downloaded version (hash: $newHash)")) {
$docsRoot = Split-Path (Split-Path $PROFILE)
$profileDirs = @(
Join-Path $docsRoot "PowerShell"
Join-Path $docsRoot "WindowsPowerShell"
)
$currentEditionDir = Split-Path $PROFILE
if (-not (Test-Path $currentEditionDir)) {
try {
New-Item -ItemType Directory -Path $currentEditionDir -Force | Out-Null
Write-Host "Created profile directory: $currentEditionDir" -ForegroundColor DarkGray
}
catch {
Write-Warning "Failed to create profile directory $currentEditionDir`: $_"
}
}
$copySuccess = 0
$copyFailed = @()
foreach ($dir in $profileDirs) {
$target = Join-Path $dir "Microsoft.PowerShell_profile.ps1"
if (Test-Path $dir) {
try {
Copy-Item -Path $tempProfile -Destination $target -Force -ErrorAction Stop
$copySuccess++
}
catch {
$copyFailed += $target
Write-Warning "Failed to copy profile to ${target}: $_"
}
}
}
if ($copySuccess -gt 0 -and $copyFailed.Count -eq 0) {
Write-Host "Profile updated ($copySuccess locations)." -ForegroundColor Green
$profileActuallyUpdated = $true
}
elseif ($copySuccess -gt 0) {
Write-Warning "Profile updated partially. Failed to write: $($copyFailed -join ', ')"
$profileActuallyUpdated = $true
}
else {
Write-Warning "Profile not updated -- no writable profile directories found."
}
}
}
else {
Write-Host "Profile .ps1 unchanged, applying config updates..." -ForegroundColor Cyan
}
# Load config for remaining phases.
$config = $null
if ($configDownloaded) {
try { $config = Get-Content $tempConfig -Raw | ConvertFrom-Json }
catch { Write-Verbose "Failed to parse downloaded config: $_" }
}
elseif (Test-Path $cachedConfig) {
try { $config = Get-Content $cachedConfig -Raw | ConvertFrom-Json }
catch {
Write-Warning "Corrupt cached config removed: $cachedConfig"
Remove-Item $cachedConfig -Force -ErrorAction SilentlyContinue
}
}
# Load terminal config for Phase 7
$terminalConfig = $null
if ($terminalConfigDownloaded) {
try { $terminalConfig = Get-Content $tempTerminalConfig -Raw | ConvertFrom-Json }
catch { Write-Verbose "Failed to parse downloaded terminal config: $_" }
}
elseif (Test-Path $cachedTerminalConfig) {
try { $terminalConfig = Get-Content $cachedTerminalConfig -Raw | ConvertFrom-Json }
catch {
Write-Warning "Corrupt cached terminal config removed: $cachedTerminalConfig"
Remove-Item $cachedTerminalConfig -Force -ErrorAction SilentlyContinue
}
}
# Apply user-settings.json overrides (never downloaded, never overwritten)
if (Test-Path $userSettingsPath) {
try {
$userSettings = Get-Utf8FileText $userSettingsPath | ConvertFrom-Json
$userSettingsParsed = $true
$userThemeOverridePresent = $null -ne $userSettings.theme
$userWindowsTerminalOverridePresent = $null -ne $userSettings.windowsTerminal
$userTerminalDefaultsOverridePresent = $null -ne $userSettings.defaults
$userKeybindingsOverridePresent = $null -ne $userSettings.keybindings
if ($config -and $userSettings.theme) {
if (-not $config.theme) {
$config | Add-Member -NotePropertyName "theme" -NotePropertyValue ([PSCustomObject]@{}) -Force
}
Merge-JsonObject $config.theme $userSettings.theme
}
if ($config -and $userSettings.windowsTerminal) {
if (-not $config.windowsTerminal) {
$config | Add-Member -NotePropertyName "windowsTerminal" -NotePropertyValue ([PSCustomObject]@{}) -Force
}
Merge-JsonObject $config.windowsTerminal $userSettings.windowsTerminal
}
if ($terminalConfig -and $userSettings.defaults) {
if (-not $terminalConfig.defaults) {
$terminalConfig | Add-Member -NotePropertyName "defaults" -NotePropertyValue ([PSCustomObject]@{}) -Force
}
Merge-JsonObject $terminalConfig.defaults $userSettings.defaults
}
if ($terminalConfig -and $userSettings.keybindings) {
if (-not $terminalConfig.keybindings) {
$terminalConfig | Add-Member -NotePropertyName "keybindings" -NotePropertyValue @() -Force
}
$terminalConfig.keybindings = @($terminalConfig.keybindings) + @($userSettings.keybindings)
}
Write-Host "User overrides applied from user-settings.json" -ForegroundColor DarkGray
}
catch {
Write-Warning "Failed to parse user-settings.json: $_"
}
}
else {
# Create the same starter user-settings template used by setup.ps1.
$userSettingsTemplate = @'
{
"_comment": "User overrides for terminal, theme, and profile behavior. Only add keys you want to override.",
"_examples": {
"theme": { "name": "catppuccin", "url": "https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/catppuccin.omp.json" },
"windowsTerminal": { "colorScheme": "One Half Dark", "cursorColor": "#ffffff" },
"defaults": {
"opacity": 90,
"font": { "size": 14 },
"backgroundImage": "%USERPROFILE%\\Pictures\\bg.png",
"backgroundImageOpacity": 0.3,
"backgroundImageStretchMode": "uniformToFill",