-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMicrosoft.PowerShell_profile.ps1
More file actions
3508 lines (3235 loc) · 154 KB
/
Microsoft.PowerShell_profile.ps1
File metadata and controls
3508 lines (3235 loc) · 154 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 agent detection: if the host sets a known agent/AI env var, set AI_AGENT so the rest of the profile only checks one name
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'
}
# Non-interactive mode detection (sandboxed/AI/CI/SSH-pipe sessions skip network calls and UI setup)
# Set AI_AGENT (or CI) when running in any AI/agent/automation context to skip interactive init
$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' })
$repo_root = "https://raw.githubusercontent.com/26zl"
$repo_name = "PowerShellPerfect"
# Cache directory outside Documents (avoids Controlled Folder Access / ransomware protection blocks)
$cacheDir = Join-Path $env:LOCALAPPDATA "PowerShellProfile"
if (-not (Test-Path $cacheDir)) { New-Item -ItemType Directory -Path $cacheDir -Force | Out-Null }
# JSONC comment-stripping regex (built via variable to avoid PS5 parser bug with [^"] in strings)
$_q = [char]34
$jsoncCommentPattern = "(?m)(?<=^([^$_q]*$_q[^$_q]*$_q)*[^$_q]*)\s*//.*`$"
# Opt-out of telemetry if running as admin (only set once)
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if ($isAdmin -and -not [System.Environment]::GetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', 'Machine')) {
[System.Environment]::SetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', 'true', [System.EnvironmentVariableTarget]::Machine)
}
# Canonical tool list - single source of truth for install, upgrade, cache invalidation, and version tracking.
# Cache: init-script filename in $cacheDir that must be deleted when the tool is upgraded (or $null).
# VerCmd: argument(s) to get the tool version for pre/post-upgrade display.
$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" }
)
# Run a scriptblock in a job with timeout; returns result or $null on timeout/failure.
# Used for native init commands where we want an explicit timeout but can pass a resolved exe path.
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 -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-Warning "Download failed (attempt $attempt/$MaxAttempts): $_ Retrying in ${BackoffSec}s..."
Start-Sleep -Seconds $BackoffSec
}
else {
throw $_
}
}
}
}
# 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
}
# Merge PSCustomObject overrides recursively so nested user/theme/terminal keys are preserved.
function Merge-JsonObject {
param(
$base,
$override
)
if (-not $base -or -not $override) { return }
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
}
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 UTF-8 stdio and explicit arguments so prompt rendering
# never depends on opaque internal init/cache state.
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, including error code, execution time, stack count, terminal width, and non-filesystem working directory.
# This is used to provide consistent context to oh-my-posh for prompt rendering without relying on opaque internal state or caches.
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 the prompt text from oh-my-posh by invoking the executable with explicit arguments and context.
# This avoids relying on opaque internal state or caches for prompt rendering, and allows consistent prompts even in non-interactive contexts (like SSH or CI) where init scripts may not run.
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 oh-my-posh cache by either deleting legacy cache files or invoking the built-in cache clear command (if available).
# Legacy cache files are detected by a special comment in the first line and are removed if found. The built-in command is used if the executable is available, and any errors during cache clearing are logged as warnings.
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
)
$tempProfile = Join-Path $env:TEMP "Microsoft.PowerShell_profile.ps1"
$tempConfig = Join-Path $env:TEMP "theme.json"
$tempTerminalConfig = Join-Path $env:TEMP "terminal-config.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
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: Hash verification (profile .ps1 only)
$oldHash = if (Test-Path $PROFILE) { (Get-FileHash -Path $PROFILE -Algorithm SHA256).Hash } else { "" }
$newHash = (Get-FileHash -Path $tempProfile -Algorithm SHA256).Hash
$profileChanged = $newHash -ne $oldHash
# 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:" -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 "Verify at https://github.com/26zl/PowerShellPerfect" -ForegroundColor Yellow
throw "Hash verification required. Re-run with -ExpectedSha256 '$combinedHash' or -SkipHashCheck."
}
$expected = $ExpectedSha256.ToUpperInvariant()
if ($combinedHash -ne $expected) {
throw "Combined hash mismatch. Expected $expected, got $combinedHash."
}
}
# Phase 3: Copy profile to PS5/PS7 dirs (only if changed)
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"
)
$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 (cache is saved AFTER all phases so a failed WT write can be retried)
$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-Content $userSettingsPath -Raw | 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 starter template so users know the file exists
$userSettingsTemplate = @'
{
"_comment": "User overrides for terminal and theme settings. 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 } },
"keybindings": [{ "keys": "ctrl+shift+t", "command": { "action": "newTab" } }]
}
}
'@
if ($PSCmdlet.ShouldProcess($userSettingsPath, "Create user-settings.json template")) {
$utf8NoBom = [System.Text.UTF8Encoding]::new($false)
[System.IO.File]::WriteAllText($userSettingsPath, $userSettingsTemplate, $utf8NoBom)
Write-Host "Created user-settings.json template in $cacheDir" -ForegroundColor Green
}
}
# Phase 4: OMP theme sync + orphan cleanup
if ($config -and $config.theme -and $config.theme.name) {
$themeName = $config.theme.name
$themeUrl = $config.theme.url
$localThemePath = Join-Path $cacheDir "$themeName.omp.json"
$currentThemeReady = $false
if (Test-Path $localThemePath) {
try {
$existingThemeContent = Get-Content $localThemePath -Raw -ErrorAction Stop
if ([string]::IsNullOrWhiteSpace($existingThemeContent)) { throw 'Theme file is empty' }
$null = $existingThemeContent | ConvertFrom-Json
$currentThemeReady = $true
}
catch {
Write-Warning "Existing OMP theme '$themeName' is invalid at '$localThemePath': $_"
}
}
$themeOverrideChanged = $userSettingsChanged -and $userThemeOverridePresent
$shouldDownloadTheme = $Force -or (-not $currentThemeReady) -or $configChanged -or $themeOverrideChanged
if ($shouldDownloadTheme -and $themeUrl) {
if ($PSCmdlet.ShouldProcess($localThemePath, "Download OMP theme '$themeName'")) {
$tempThemePath = Join-Path $cacheDir ("{0}.{1}.download" -f $themeName, [System.IO.Path]::GetRandomFileName())
try {
Invoke-DownloadWithRetry -Uri $themeUrl -OutFile $tempThemePath
$downloadedThemeContent = Get-Content $tempThemePath -Raw -ErrorAction Stop
if ([string]::IsNullOrWhiteSpace($downloadedThemeContent)) { throw 'Downloaded theme file is empty' }
$null = $downloadedThemeContent | ConvertFrom-Json
Move-Item -Path $tempThemePath -Destination $localThemePath -Force
Write-Host "OMP theme '$themeName' updated." -ForegroundColor Green
$currentThemeReady = $true
}
catch {
Write-Warning "Failed to download/validate OMP theme: $_"
$phaseErrors += "OMP theme download: $_"
}
finally {
Remove-Item $tempThemePath -Force -ErrorAction SilentlyContinue
}
}
}
elseif ($shouldDownloadTheme -and -not $themeUrl -and -not $currentThemeReady) {
Write-Warning "OMP theme '$themeName' is missing locally and no download URL is configured."
$phaseErrors += "OMP theme missing URL: $themeName"
}
# Orphan cleanup - remove *.omp.json files that don't match current theme
if (-not $currentThemeReady -and (Test-Path $localThemePath)) {
try {
$currentThemeContent = Get-Content $localThemePath -Raw -ErrorAction Stop
if ([string]::IsNullOrWhiteSpace($currentThemeContent)) { throw 'Theme file is empty' }
$null = $currentThemeContent | ConvertFrom-Json
$currentThemeReady = $true
}
catch {
Write-Warning "Skipping orphan cleanup because current OMP theme '$themeName' is still invalid: $_"
}
}
if ($currentThemeReady) {
$ompFiles = Get-ChildItem -Path $cacheDir -Filter "*.omp.json" -ErrorAction SilentlyContinue
foreach ($file in $ompFiles) {
if ($file.Name -ne "$themeName.omp.json") {
if ($PSCmdlet.ShouldProcess($file.FullName, "Remove orphaned OMP theme")) {
Remove-Item $file.FullName -Force -ErrorAction SilentlyContinue
Write-Host "Removed orphaned theme: $($file.Name)" -ForegroundColor DarkGray
}
}
}
}
}
# Phase 5: Cache invalidation - clear all tool init caches declared in $script:ProfileTools
if ($profileChanged -or $configChanged) {
foreach ($tool in $script:ProfileTools) {
if ($tool.Cache) {
$cachePath = Join-Path $cacheDir $tool.Cache
if (Test-Path $cachePath) {
if ($PSCmdlet.ShouldProcess($cachePath, "Invalidate $($tool.Name) init cache")) {
Remove-Item $cachePath -Force -ErrorAction SilentlyContinue
Write-Host "$($tool.Name) init cache cleared." -ForegroundColor DarkGray
}
}
}
}
}
# Phase 6: Windows Terminal sync
$terminalOverridesChanged = $userSettingsChanged -and ($userWindowsTerminalOverridePresent -or $userTerminalDefaultsOverridePresent -or $userKeybindingsOverridePresent)
if (($Force -or $profileChanged -or $configChanged -or $terminalConfigChanged -or $terminalOverridesChanged) -and (($config -and $config.windowsTerminal) -or $terminalConfig)) {
$wtSettingsPath = Join-Path $env:LOCALAPPDATA "Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json"
if (Test-Path $wtSettingsPath) {
if ($PSCmdlet.ShouldProcess($wtSettingsPath, "Update Windows Terminal settings")) {
try {
$timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
$backupPath = "$wtSettingsPath.$timestamp.bak"
Copy-Item $wtSettingsPath $backupPath -Force
Write-Host "WT backup: $backupPath" -ForegroundColor DarkGray
# Cleanup old WT backups (keep last 5)
$wtLocalState = Split-Path $wtSettingsPath
$oldBackups = Get-ChildItem -Path $wtLocalState -Filter "settings.json.*.bak" -ErrorAction SilentlyContinue |
Sort-Object LastWriteTime -Descending | Select-Object -Skip 5
foreach ($old in $oldBackups) {
Remove-Item $old.FullName -Force -ErrorAction SilentlyContinue
}
# Read WT settings with retry (race condition mitigation if WT is writing)
$wt = $null
for ($wtAttempt = 1; $wtAttempt -le 2; $wtAttempt++) {
try {
$wtRaw = (Get-Content $wtSettingsPath -Raw) -replace $jsoncCommentPattern, ''
$wt = $wtRaw | ConvertFrom-Json
break
}
catch {
if ($wtAttempt -lt 2) {
Write-Warning "WT settings parse failed, retrying in 1s..."
Start-Sleep -Seconds 1
}
else { throw }
}
}
if (-not $wt) { $wt = [PSCustomObject]@{} }
if (-not $wt.profiles) {
$wt | Add-Member -NotePropertyName "profiles" -NotePropertyValue ([PSCustomObject]@{}) -Force
}
if (-not $wt.profiles.defaults) {
$wt.profiles | Add-Member -NotePropertyName "defaults" -NotePropertyValue ([PSCustomObject]@{}) -Force
}
$defaults = $wt.profiles.defaults
# Terminal-config defaults first (font, opacity, scrollbar, etc.)
if ($terminalConfig -and $terminalConfig.defaults) {
$terminalConfig.defaults.PSObject.Properties | ForEach-Object {
$defaults | Add-Member -NotePropertyName $_.Name -NotePropertyValue $_.Value -Force
}
}
# Theme colors second (always win over terminal defaults)
if ($config -and $config.windowsTerminal) {
$schemeName = $config.windowsTerminal.colorScheme
if ($schemeName) {
$defaults | Add-Member -NotePropertyName "colorScheme" -NotePropertyValue $schemeName -Force
}
$cursorColor = $config.windowsTerminal.cursorColor
if ($cursorColor) {
$defaults | Add-Member -NotePropertyName "cursorColor" -NotePropertyValue $cursorColor -Force
}
# Upsert scheme definition
$schemeDef = $config.windowsTerminal.scheme
if ($schemeDef) {
if (-not $wt.schemes) {
$wt | Add-Member -NotePropertyName "schemes" -NotePropertyValue @() -Force
}
$schemeDefName = if ($schemeDef.name) { $schemeDef.name } else { $schemeName }
$wt.schemes = @(@($wt.schemes | Where-Object { $_ -and $_.name -ne $schemeDefName }) + ([PSCustomObject]$schemeDef))
}
}
# Keybindings last
if ($terminalConfig -and $terminalConfig.keybindings) {
if (-not $wt.actions) {
$wt | Add-Member -NotePropertyName "actions" -NotePropertyValue @() -Force
}
foreach ($kb in $terminalConfig.keybindings) {
if (-not $kb -or [string]::IsNullOrWhiteSpace($kb.keys)) { continue }
$bindingId = "User.profile.$($kb.keys -replace '[^a-zA-Z0-9]', '')"
if ($wt.PSObject.Properties['keybindings']) {
# New WT format: separate keybindings array references actions by id
$existingIds = @($wt.keybindings | Where-Object { $_.keys -eq $kb.keys } | ForEach-Object { $_.id })
if ($existingIds.Count -gt 0) {
$wt.actions = @($wt.actions | Where-Object { $_ -and ($existingIds -notcontains $_.id) })
$wt.keybindings = @($wt.keybindings | Where-Object { $_ -and $_.keys -ne $kb.keys })
}
$wt.actions = @($wt.actions) + ([PSCustomObject]@{ command = $kb.command; id = $bindingId })
$wt.keybindings = @($wt.keybindings) + ([PSCustomObject]@{ id = $bindingId; keys = $kb.keys })
}
else {
# Old WT format: keys directly in actions
$wt.actions = @($wt.actions | Where-Object { $_ -and $_.keys -ne $kb.keys })
$wt.actions = @($wt.actions) + ([PSCustomObject]@{ keys = $kb.keys; command = $kb.command })
}
}
}
# Ensure PowerShell profiles launch with -NoLogo
if ($wt.profiles.list) {
foreach ($prof in @($wt.profiles.list)) {
if (-not $prof) { continue }
$cmd = if ($prof.commandline) { $prof.commandline } else { '' }
$src = if ($prof.source) { $prof.source } else { '' }
$isPwsh = $cmd -match 'pwsh' -or $src -match 'Windows\.Terminal\.PowerShellCore'
$isPS5 = $cmd -match 'powershell\.exe' -or $prof.name -match 'Windows PowerShell'
if ($isPwsh -or $isPS5) {
if ($cmd -and $cmd -notmatch '-NoLogo' -and $cmd -notmatch '(?i)-(Command|File|EncodedCommand)') {