-
-
Notifications
You must be signed in to change notification settings - Fork 467
Expand file tree
/
Copy pathMicrosoft.PowerShell_profile.ps1
More file actions
792 lines (659 loc) · 24.4 KB
/
Copy pathMicrosoft.PowerShell_profile.ps1
File metadata and controls
792 lines (659 loc) · 24.4 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
### Chris Titus Tech's PowerShell profile
function Enable-Tls12 {
try {
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
} catch {
Write-Verbose "Unable to enable TLS 1.2 explicitly: $_"
}
}
Enable-Tls12
$script:ProfileRoot = if ($PSScriptRoot) { $PSScriptRoot } else { Split-Path -Path $PROFILE.CurrentUserCurrentHost -Parent }
$script:CustomProfile = Join-Path -Path $script:ProfileRoot -ChildPath 'CTTcustom.ps1'
if (Test-Path -Path $script:CustomProfile -PathType Leaf) {
. $script:CustomProfile
}
function Test-InteractiveShell {
try {
return $Host.Name -eq 'ConsoleHost' -and
-not [Console]::IsInputRedirected -and
-not [Console]::IsOutputRedirected
} catch {
return $false
}
}
function Get-ProfileDir {
switch ($PSVersionTable.PSEdition) {
'Core' { Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'PowerShell'; break }
'Desktop' { Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'WindowsPowerShell'; break }
default {
throw "Unsupported PowerShell edition: $($PSVersionTable.PSEdition)"
}
}
}
function Test-Command {
param([Parameter(Mandatory)][string]$Name)
$null -ne (Get-Command -Name $Name -ErrorAction SilentlyContinue)
}
function Save-UriToFile {
param(
[Parameter(Mandatory)][string]$Uri,
[Parameter(Mandatory)][string]$OutFile
)
$client = New-Object System.Net.WebClient
try {
$client.DownloadFile($Uri, $OutFile)
} finally {
$client.Dispose()
}
}
function Get-UriContent {
param([Parameter(Mandatory)][string]$Uri)
$client = New-Object System.Net.WebClient
try {
$client.DownloadString($Uri)
} finally {
$client.Dispose()
}
}
$isInteractiveShell = Test-InteractiveShell
$debug = if ($null -ne $debug_Override) { [bool]$debug_Override } else { $false }
$repo_root = if ($repo_root_Override) { $repo_root_Override } else { 'https://raw.githubusercontent.com/ChrisTitusTech' }
$profileDir = Get-ProfileDir
$timeFilePath = if ($timeFilePath_Override) { $timeFilePath_Override } else { Join-Path $profileDir 'LastExecutionTime.txt' }
$updateInterval = if ($null -ne $updateInterval_Override) { [int]$updateInterval_Override } else { 7 }
$showHelpOnLaunch = if ($null -ne $show_help_Override) { [bool]$show_help_Override } else { $false }
function Debug-Message {
if (Get-Command -Name 'Debug-Message_Override' -ErrorAction SilentlyContinue) {
Debug-Message_Override
return
}
Write-Host '#######################################' -ForegroundColor Red
Write-Host '# Debug mode enabled #' -ForegroundColor Red
Write-Host '# ONLY FOR DEVELOPMENT #' -ForegroundColor Red
Write-Host '# Run Update-Profile to reset #' -ForegroundColor Red
Write-Host '#######################################' -ForegroundColor Red
}
if ($debug) {
Debug-Message
}
function Test-ProfileUpdateDue {
param(
[Parameter(Mandatory)][string]$Path,
[Parameter(Mandatory)][int]$IntervalDays
)
if ($IntervalDays -lt 0 -or -not (Test-Path -Path $Path -PathType Leaf)) {
return $true
}
$rawDate = (Get-Content -Path $Path -Raw -ErrorAction SilentlyContinue).Trim()
if ([string]::IsNullOrWhiteSpace($rawDate)) {
return $true
}
$lastRun = [datetime]::MinValue
if (-not [datetime]::TryParseExact(
$rawDate,
'yyyy-MM-dd',
[Globalization.CultureInfo]::InvariantCulture,
[Globalization.DateTimeStyles]::None,
[ref]$lastRun
)) {
return $true
}
return ((Get-Date).Date - $lastRun.Date).TotalDays -ge $IntervalDays
}
function Test-ProfileIsSymlink {
$profileItem = Get-Item -LiteralPath $PROFILE.CurrentUserCurrentHost -Force -ErrorAction SilentlyContinue
return $profileItem -and $profileItem.LinkType -eq 'SymbolicLink'
}
function Update-Profile {
[CmdletBinding(SupportsShouldProcess)]
[OutputType([bool])]
param([switch]$Force)
if (Get-Command -Name 'Update-Profile_Override' -ErrorAction SilentlyContinue) {
Update-Profile_Override @PSBoundParameters
return $true
}
$url = "$repo_root/powershell-profile/main/Microsoft.PowerShell_profile.ps1"
$target = $PROFILE.CurrentUserCurrentHost
$tempFile = Join-Path $env:TEMP 'Microsoft.PowerShell_profile.ps1'
try {
Save-UriToFile -Uri $url -OutFile $tempFile
$targetExists = Test-Path -Path $target -PathType Leaf
$oldHash = if ($targetExists) { (Get-FileHash -Path $target).Hash } else { $null }
$newHash = (Get-FileHash -Path $tempFile).Hash
if (-not $Force -and $targetExists -and $oldHash -eq $newHash) {
if ($isInteractiveShell) {
Write-Host 'Profile is up to date.' -ForegroundColor Green
}
return $true
}
if ($PSCmdlet.ShouldProcess($target, 'Update PowerShell profile')) {
$targetDir = Split-Path -Path $target -Parent
if (-not (Test-Path -Path $targetDir)) {
New-Item -Path $targetDir -ItemType Directory -Force | Out-Null
}
Copy-Item -Path $tempFile -Destination $target -Force
Write-Host 'Profile has been updated. Restart your shell to use the new version.' -ForegroundColor Magenta
}
return $true
} catch {
Write-Warning "Unable to check for profile updates: $_"
return $false
} finally {
Remove-Item -Path $tempFile -ErrorAction SilentlyContinue
}
}
function Invoke-ScheduledProfileUpdate {
if ($debug -or
-not $isInteractiveShell -or
(Test-ProfileIsSymlink) -or
-not (Test-ProfileUpdateDue -Path $timeFilePath -IntervalDays $updateInterval)) {
return
}
if (Update-Profile) {
$timeDir = Split-Path -Path $timeFilePath -Parent
if (-not (Test-Path -Path $timeDir)) {
New-Item -Path $timeDir -ItemType Directory -Force | Out-Null
}
Get-Date -Format 'yyyy-MM-dd' | Set-Content -Path $timeFilePath
}
}
function Update-PowerShell {
[CmdletBinding(SupportsShouldProcess)]
param()
if (Get-Command -Name 'Update-PowerShell_Override' -ErrorAction SilentlyContinue) {
Update-PowerShell_Override @PSBoundParameters
return
}
if (-not (Test-Command winget)) {
Write-Warning 'winget is required to update PowerShell automatically.'
return
}
try {
$release = Invoke-RestMethod -Uri 'https://api.github.com/repos/PowerShell/PowerShell/releases/latest' -ErrorAction Stop
$currentVersion = [version]$PSVersionTable.PSVersion
$latestVersion = [version]($release.tag_name -replace '^v', '')
if ($currentVersion -ge $latestVersion) {
Write-Host "PowerShell $currentVersion is up to date." -ForegroundColor Green
return
}
if ($PSCmdlet.ShouldProcess("PowerShell $currentVersion", "Upgrade to $latestVersion")) {
winget upgrade --id Microsoft.PowerShell --exact --accept-source-agreements --accept-package-agreements
if ($LASTEXITCODE -ne 0) {
Write-Error "winget failed to update PowerShell. Exit code: $LASTEXITCODE"
return
}
Write-Host 'PowerShell has been updated. Restart your shell to use the new version.' -ForegroundColor Magenta
}
} catch {
Write-Error "Failed to update PowerShell. Error: $_"
}
}
function Clear-Cache {
[CmdletBinding(SupportsShouldProcess)]
param()
if (Get-Command -Name 'Clear-Cache_Override' -ErrorAction SilentlyContinue) {
Clear-Cache_Override @PSBoundParameters
return
}
$paths = @(
"$env:SystemRoot\Prefetch\*",
"$env:SystemRoot\Temp\*",
"$env:TEMP\*",
"$env:LOCALAPPDATA\Microsoft\Windows\INetCache\*"
)
foreach ($path in $paths) {
if ($PSCmdlet.ShouldProcess($path, 'Remove cached files')) {
Remove-Item -Path $path -Recurse -Force -ErrorAction SilentlyContinue
}
}
}
function Initialize-OptionalModule {
if (-not $isInteractiveShell) {
return
}
if (Get-Module -ListAvailable -Name Terminal-Icons) {
Import-Module -Name Terminal-Icons -ErrorAction SilentlyContinue
} elseif ($isInteractiveShell) {
Write-Warning 'Terminal-Icons module is not installed. Run setup.ps1 to install dependencies.'
}
$chocolateyProfile = if ($env:ChocolateyInstall) {
Join-Path $env:ChocolateyInstall 'helpers\chocolateyProfile.psm1'
} else {
$null
}
if ($chocolateyProfile -and (Test-Path -Path $chocolateyProfile -PathType Leaf)) {
Import-Module $chocolateyProfile -ErrorAction SilentlyContinue
}
}
function Resolve-Editor {
if ($EDITOR_Override) {
return $EDITOR_Override
}
foreach ($candidate in 'nvim', 'pvim', 'vim', 'vi', 'code', 'codium', 'notepad++', 'sublime_text') {
if (Test-Command $candidate) {
return $candidate
}
}
return 'notepad'
}
Initialize-OptionalModule
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
$EDITOR = Resolve-Editor
Set-Alias -Name vim -Value $EDITOR -Force
if ($isInteractiveShell) {
try {
$adminSuffix = if ($isAdmin) { ' [ADMIN]' } else { '' }
$Host.UI.RawUI.WindowTitle = "PowerShell $($PSVersionTable.PSVersion)$adminSuffix"
} catch {
Write-Verbose "Unable to set console title: $_"
}
}
function prompt {
$marker = if ($isAdmin) { '#' } else { '$' }
"[$(Get-Location)] $marker "
}
function Edit-Profile {
& $EDITOR $PROFILE.CurrentUserAllHosts
}
Set-Alias -Name ep -Value Edit-Profile -Force
function Invoke-Profile {
. $PROFILE.CurrentUserCurrentHost
}
function touch {
param([Parameter(Mandatory)][string]$File)
if (Test-Path -Path $File) {
(Get-Item -Path $File).LastWriteTime = Get-Date
} else {
New-Item -Path $File -ItemType File -Force | Out-Null
}
}
function mkcd {
param([Parameter(Mandatory)][string]$Path)
New-Item -Path $Path -ItemType Directory -Force | Out-Null
Set-Location -Path $Path
}
function ff {
param([Parameter(Mandatory)][string]$Name)
Get-ChildItem -Recurse -Filter "*$Name*" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty FullName
}
function pubip {
(Get-UriContent -Uri 'https://ifconfig.me/ip').Trim()
}
function winutil {
& ([ScriptBlock]::Create((Invoke-RestMethod -Uri 'https://christitus.com/win'))) @args
}
function winutildev {
if (Get-Command -Name 'WinUtilDev_Override' -ErrorAction SilentlyContinue) {
WinUtilDev_Override @args
return
}
& ([ScriptBlock]::Create((Invoke-RestMethod -Uri 'https://christitus.com/windev'))) @args
}
function windev {
$winutilRepo = Join-Path ([Environment]::GetFolderPath('UserProfile')) 'github\winutil'
$compileScript = Join-Path $winutilRepo 'Compile.ps1'
$compiledScript = Join-Path $winutilRepo 'winutil.ps1'
if (-not (Test-Path -LiteralPath $compileScript -PathType Leaf)) {
throw "WinUtil's Compile.ps1 was not found at '$compileScript'."
}
Push-Location -LiteralPath $winutilRepo
try {
& $compileScript
if (-not $?) {
throw 'WinUtil compilation failed.'
}
} finally {
Pop-Location
}
if (-not (Test-Path -LiteralPath $compiledScript -PathType Leaf)) {
throw "WinUtil compilation did not create '$compiledScript'."
}
$shell = if (Test-Command pwsh) { 'pwsh.exe' } else { 'powershell.exe' }
Start-Process -FilePath $shell -WorkingDirectory $winutilRepo -ArgumentList @(
'-NoProfile',
'-ExecutionPolicy', 'Bypass',
'-File', $compiledScript
)
}
function admin {
$cwd = (Get-Location).ProviderPath
$shell = if (Test-Command pwsh) { 'pwsh.exe' } else { 'powershell.exe' }
$shellArgs = if ($args.Count -gt 0) { @('-NoExit', '-Command', ($args -join ' ')) } else { @('-NoExit') }
if (Test-Command wt) {
Start-Process wt -Verb RunAs -ArgumentList (@('-d', $cwd, $shell) + $shellArgs)
} else {
Start-Process $shell -Verb RunAs -WorkingDirectory $cwd -ArgumentList $shellArgs
}
}
Set-Alias -Name su -Value admin -Force
function uptime {
$boot = if (Get-Command Get-Uptime -ErrorAction SilentlyContinue) {
Get-Uptime -Since
} else {
(Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime
}
(Get-Date) - $boot | Select-Object Days, Hours, Minutes, Seconds
}
function unzip {
param([Parameter(Mandatory)][string]$File)
if (-not (Test-Path -Path $File -PathType Leaf)) {
Write-Error "File not found: $File"
return
}
Expand-Archive -Path $File -DestinationPath (Get-Location) -Force
}
function grep {
[CmdletBinding()]
param(
[Parameter(Mandatory, Position = 0)][string]$Pattern,
[Parameter(Position = 1)][string]$Path,
[Parameter(ValueFromPipeline)][object]$InputObject
)
begin {
$pipelineInput = [System.Collections.Generic.List[object]]::new()
}
process {
if ($PSBoundParameters.ContainsKey('InputObject')) {
$pipelineInput.Add($InputObject)
}
}
end {
if ($Path) {
Get-ChildItem -Path $Path -Recurse -File -ErrorAction SilentlyContinue | Select-String -Pattern $Pattern
} elseif ($pipelineInput.Count -gt 0) {
$pipelineInput | Select-String -Pattern $Pattern
} else {
Write-Error 'Usage: grep <pattern> [path] or pipe input to grep'
}
}
}
function df { Get-Volume }
function sed {
param(
[Parameter(Mandatory)][string]$File,
[Parameter(Mandatory)][string]$Find,
[Parameter(Mandatory)][string]$Replace
)
(Get-Content -Path $File).Replace($Find, $Replace) | Set-Content -Path $File
}
function which {
param([Parameter(Mandatory)][string]$Name)
Get-Command -Name $Name | Select-Object -ExpandProperty Definition
}
function export {
param(
[Parameter(Mandatory)][string]$Name,
[Parameter(Mandatory)][string]$Value
)
Set-Item -Path "env:$Name" -Value $Value -Force
}
function pkill {
param([Parameter(Mandatory)][string]$Name)
Get-Process -Name $Name -ErrorAction SilentlyContinue | Stop-Process -Force
}
function pgrep {
param([Parameter(Mandatory)][string]$Name)
Get-Process -Name $Name -ErrorAction SilentlyContinue
}
function head {
param([Parameter(Mandatory)][string]$Path, [int]$n = 10)
Get-Content -Path $Path -Head $n
}
function tail {
param([Parameter(Mandatory)][string]$Path, [int]$n = 10, [switch]$f)
Get-Content -Path $Path -Tail $n -Wait:$f
}
function nf {
param([Parameter(Mandatory)][string]$Name)
New-Item -ItemType File -Path . -Name $Name -Force | Out-Null
}
function trash {
param([Parameter(Mandatory)][string]$Path)
$resolvedPath = Resolve-Path -LiteralPath $Path -ErrorAction SilentlyContinue
if (-not $resolvedPath) {
Write-Error "Item not found: $Path"
return
}
$fullPath = $resolvedPath.ProviderPath
$item = Get-Item -LiteralPath $fullPath
$parentPath = if ($item.PSIsContainer) {
if ($item.Parent) { $item.Parent.FullName } else { Split-Path -Path $item.FullName -Parent }
} else {
$item.DirectoryName
}
if ([string]::IsNullOrWhiteSpace($parentPath)) {
Write-Error "Cannot move root path to Recycle Bin: $fullPath"
return
}
$shell = New-Object -ComObject 'Shell.Application'
$shellFolder = $shell.NameSpace($parentPath)
$shellItem = if ($shellFolder) { $shellFolder.ParseName($item.Name) } else { $null }
if ($shellItem) {
$shellItem.InvokeVerb('delete')
} else {
Write-Error "Could not move item to Recycle Bin: $fullPath"
}
}
function docs {
Set-Location -Path ([Environment]::GetFolderPath('MyDocuments'))
}
function dtop {
Set-Location -Path ([Environment]::GetFolderPath('Desktop'))
}
function k9 { param([Parameter(Mandatory)][string]$Name) pkill $Name }
function la { Get-ChildItem | Format-Table -AutoSize }
function ll { Get-ChildItem -Force | Format-Table -AutoSize }
function gs { git status }
function ga { git add . }
function gc { git commit -m ($args -join ' ') }
function gpush { git push @args }
function gpull { git pull @args }
function gcl { git clone @args }
function g {
if (Get-Command __zoxide_z -ErrorAction SilentlyContinue) {
__zoxide_z github
} elseif (Test-Path -Path "$HOME\github") {
Set-Location "$HOME\github"
}
}
function gcom {
git add .
git commit -m ($args -join ' ')
}
function lazyg {
git add .
git commit -m ($args -join ' ')
git push
}
function sysinfo { Get-ComputerInfo }
function flushdns {
Clear-DnsClientCache
Write-Host 'DNS has been flushed'
}
function cpy { Set-Clipboard ($args -join ' ') }
function pst { Get-Clipboard }
function Set-PSReadLineOptionsCompat {
[CmdletBinding(SupportsShouldProcess)]
param([Parameter(Mandatory)][hashtable]$Options)
$safeOptions = $Options.Clone()
if ($PSVersionTable.PSEdition -ne 'Core') {
$safeOptions.Remove('PredictionSource')
$safeOptions.Remove('PredictionViewStyle')
}
if ($PSCmdlet.ShouldProcess('PSReadLine', 'Set PSReadLine options')) {
Set-PSReadLineOption @safeOptions
}
}
function Set-PredictionSource {
[CmdletBinding(SupportsShouldProcess)]
param()
if (Get-Command -Name 'Set-PredictionSource_Override' -ErrorAction SilentlyContinue) {
Set-PredictionSource_Override
return
}
if ($PSCmdlet.ShouldProcess('PSReadLine', 'Set prediction source')) {
if ($PSVersionTable.PSEdition -eq 'Core') {
Set-PSReadLineOption -PredictionSource HistoryAndPlugin
}
Set-PSReadLineOption -MaximumHistoryCount 10000
}
}
function Initialize-PSReadLine {
if (-not $isInteractiveShell -or -not (Get-Module -ListAvailable -Name PSReadLine)) {
return
}
$options = @{
EditMode = 'Windows'
HistoryNoDuplicates = $true
HistorySearchCursorMovesToEnd = $true
PredictionSource = 'History'
PredictionViewStyle = 'ListView'
BellStyle = 'None'
Colors = @{
Command = '#87CEEB'
Parameter = '#98FB98'
Operator = '#FFB6C1'
Variable = '#DDA0DD'
String = '#FFDAB9'
Number = '#B0E0E6'
Type = '#F0E68C'
Comment = '#D3D3D3'
Keyword = '#8367c7'
Error = '#FF6347'
}
}
Set-PSReadLineOptionsCompat -Options $options
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward
Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete
Set-PSReadLineKeyHandler -Chord 'Ctrl+d' -Function DeleteChar
Set-PSReadLineKeyHandler -Chord 'Ctrl+w' -Function BackwardDeleteWord
Set-PSReadLineKeyHandler -Chord 'Alt+d' -Function DeleteWord
Set-PSReadLineKeyHandler -Chord 'Ctrl+LeftArrow' -Function BackwardWord
Set-PSReadLineKeyHandler -Chord 'Ctrl+RightArrow' -Function ForwardWord
Set-PSReadLineKeyHandler -Chord 'Ctrl+z' -Function Undo
Set-PSReadLineKeyHandler -Chord 'Ctrl+y' -Function Redo
Set-PSReadLineOption -AddToHistoryHandler {
param([string]$line)
$line -notmatch '(?i)(password|secret|token|apikey|connectionstring)'
}
Set-PredictionSource
}
function Register-CustomCompletion {
if (-not $isInteractiveShell) {
return
}
$completionMap = @{
git = @('status', 'add', 'commit', 'push', 'pull', 'clone', 'checkout')
npm = @('install', 'start', 'run', 'test', 'build')
deno = @('run', 'compile', 'bundle', 'test', 'lint', 'fmt', 'cache', 'info', 'doc', 'upgrade')
}
Register-ArgumentCompleter -Native -CommandName git, npm, deno -ScriptBlock {
param($wordToComplete, $commandAst, $cursorPosition)
$null = $cursorPosition
$completionWord = $wordToComplete
$map = $completionMap
$command = $commandAst.CommandElements[0].Value
if ($map.ContainsKey($command)) {
$map[$command] |
Where-Object { $_ -like "$completionWord*" } |
ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }
}
}.GetNewClosure()
if (Test-Command dotnet) {
Register-ArgumentCompleter -Native -CommandName dotnet -ScriptBlock {
param($wordToComplete, $commandAst, $cursorPosition)
$null = $wordToComplete
dotnet complete --position $cursorPosition $commandAst.ToString() |
ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }
}
}
}
function Resolve-OhMyPoshTheme {
$candidates = @(
$env:POSH_THEME,
(Join-Path $profileDir 'cobalt2.omp.json'),
(Join-Path $HOME 'cobalt2.omp.json')
) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
foreach ($candidate in $candidates) {
if (Test-Path -Path $candidate -PathType Leaf) {
return $candidate
}
}
return $null
}
function Initialize-PromptTool {
if (-not $isInteractiveShell) {
return
}
if (Get-Command -Name 'Get-Theme_Override' -ErrorAction SilentlyContinue) {
Get-Theme_Override
} elseif (Test-Command oh-my-posh) {
$theme = Resolve-OhMyPoshTheme
if ($theme) {
oh-my-posh init pwsh --config $theme | Invoke-Expression
} elseif ($isInteractiveShell) {
Write-Warning 'Oh My Posh theme not found. Run setup.ps1 to install cobalt2.omp.json.'
}
} elseif ($isInteractiveShell) {
Write-Warning 'oh-my-posh is not installed. Run setup.ps1 to install dependencies.'
}
if (Test-Command zoxide) {
Invoke-Expression (& { (zoxide init --cmd z powershell | Out-String) })
} elseif ($isInteractiveShell) {
Write-Warning 'zoxide is not installed. Run setup.ps1 to install dependencies.'
}
}
function Show-Help {
@'
PowerShell Profile Help
=======================
Profile:
Edit-Profile Open the current user's all-hosts profile for editing.
Invoke-Profile Reload this profile in the current session.
Update-Profile Check for profile updates.
Update-PowerShell Check for the latest PowerShell release and update with winget.
Git:
g Go to the GitHub directory with zoxide fallback.
ga git add .
gc <message> git commit -m <message>
gcl <repo> git clone <repo>
gcom <message> git add .; git commit -m <message>
gp/gpush git push
gpull git pull
gs git status
lazyg <message> git add .; git commit -m <message>; git push
Shortcuts:
cpy <text> Copy text to the clipboard.
df Show volume information.
docs/dtop Go to Documents/Desktop.
ff <name> Find files recursively by name.
flushdns Clear the DNS cache.
grep <regex> [p] Search files or piped input.
head/tail Show the first or last lines of a file.
k9/pkill <name> Kill processes by name.
la/ll List visible/all files.
mkcd <dir> Create and enter a directory.
nf/touch <file> Create a file.
pgrep <name> Find processes by name.
pst Paste clipboard text.
sed <f> <a> <b> Replace text in a file.
sysinfo Show system information.
unzip <file> Extract a zip file here.
uptime Show system uptime.
which <name> Show command path.
windev Compile and run the local WinUtil checkout.
winutil Run the latest WinUtil release script.
winutildev Run the latest WinUtil prerelease script.
'@ | Write-Host
}
Set-Alias -Name gp -Value gpush -Force
Initialize-PSReadLine
Register-CustomCompletion
Initialize-PromptTool
Invoke-ScheduledProfileUpdate
if ($showHelpOnLaunch) {
Show-Help
} elseif ($isInteractiveShell) {
Write-Host "Use 'Show-Help' to display help" -ForegroundColor Yellow
}