-
-
Notifications
You must be signed in to change notification settings - Fork 458
Expand file tree
/
Copy pathMicrosoft.PowerShell_profile.ps1
More file actions
762 lines (664 loc) · 32.9 KB
/
Microsoft.PowerShell_profile.ps1
File metadata and controls
762 lines (664 loc) · 32.9 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
### PowerShell Profile Refactor
### Version 1.04 - Refactored
$debug = $false
#################################################################################################################################
############ ############
############ !!! WARNING: !!! ############
############ ############
############ DO NOT MODIFY THIS FILE. THIS FILE IS HASHED AND UPDATED AUTOMATICALLY. ############
############ ANY CHANGES MADE TO THIS FILE WILL BE OVERWRITTEN BY COMMITS TO ############
############ https://github.com/ChrisTitusTech/powershell-profile.git. ############
############ ############
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#
############ ############
############ TO ADD YOUR OWN CODE OR IF YOU WANT TO OVERRIDE ANY OF THESE VARIABLES ############
############ OR FUNCTIONS. USE THE Edit-Profile FUNCTION TO CREATE YOUR OWN profile.ps1 FILE. ############
############ TO OVERRIDE IN YOUR NEW profile.ps1 FILE, REWRITE THE VARIABLE ############
############ OR FUNCTION, ADDING "_Override" TO THE NAME. ############
############ ############
############ THE FOLLOWING VARIABLES RESPECT _Override: ############
############ $EDITOR_Override ############
############ $debug_Override ############
############ $repo_root_Override [To point to a fork, for example] ############
############ $timeFilePath_Override ############
############ $updateInterval_Override ############
############ ############
############ THE FOLLOWING FUNCTIONS RESPECT _Override: ############
############ Debug-Message_Override ############
############ Update-Profile_Override ############
############ Update-PowerShell_Override ############
############ Clear-Cache_Override ############
############ Get-Theme_Override ############
############ WinUtilDev_Override [To call a fork, for example] ############
############ Set-PredictionSource ############
#################################################################################################################################
if ($debug_Override){
# If variable debug_Override is defined in profile.ps1 file
# then use it instead
$debug = $debug_Override
} else {
$debug = $false
}
# Define the path to the file that stores the last execution time
if ($repo_root_Override){
# If variable $repo_root_Override is defined in profile.ps1 file
# then use it instead
$repo_root = $repo_root_Override
} else {
$repo_root = "https://raw.githubusercontent.com/ChrisTitusTech"
}
# Helper function for cross-edition compatibility
function Get-ProfileDir {
if ($PSVersionTable.PSEdition -eq "Core") {
return [Environment]::GetFolderPath("MyDocuments") + "\PowerShell"
} elseif ($PSVersionTable.PSEdition -eq "Desktop") {
return [Environment]::GetFolderPath("MyDocuments") + "\WindowsPowerShell"
} else {
Write-Error "Unsupported PowerShell edition: $($PSVersionTable.PSEdition)"
return $null
}
}
# Define the path to the file that stores the last execution time
if ($timeFilePath_Override){
# If variable $timeFilePath_Override is defined in profile.ps1 file
# then use it instead
$timeFilePath = $timeFilePath_Override
} else {
$profileDir = Get-ProfileDir
$timeFilePath = "$profileDir\LastExecutionTime.txt"
}
# Define the update interval in days, set to -1 to always check
if ($updateInterval_Override){
# If variable $updateInterval_Override is defined in profile.ps1 file
# then use it instead
$updateInterval = $updateInterval_Override
} else {
$updateInterval = 7
}
function Debug-Message{
# If function "Debug-Message_Override" is defined in profile.ps1 file
# then call it instead.
if (Get-Command -Name "Debug-Message_Override" -ErrorAction SilentlyContinue) {
Debug-Message_Override
} else {
Write-Host "#######################################" -ForegroundColor Red
Write-Host "# Debug mode enabled #" -ForegroundColor Red
Write-Host "# ONLY FOR DEVELOPMENT #" -ForegroundColor Red
Write-Host "# #" -ForegroundColor Red
Write-Host "# IF YOU ARE NOT DEVELOPING #" -ForegroundColor Red
Write-Host "# JUST RUN \`Update-Profile\` #" -ForegroundColor Red
Write-Host "# to discard all changes #" -ForegroundColor Red
Write-Host "# and update to the latest profile #" -ForegroundColor Red
Write-Host "# version #" -ForegroundColor Red
Write-Host "#######################################" -ForegroundColor Red
}
}
if ($debug) {
Debug-Message
}
# Opt-out of telemetry before doing anything, only if PowerShell is run as admin
if ([bool]([System.Security.Principal.WindowsIdentity]::GetCurrent()).IsSystem) {
[System.Environment]::SetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', 'true', [System.EnvironmentVariableTarget]::Machine)
}
# Initial GitHub.com connectivity check
function Test-GitHubConnection {
if ($PSVersionTable.PSEdition -eq "Core") {
# If PowerShell Core, use a 1 second timeout
return Test-Connection github.com -Count 1 -Quiet -TimeoutSeconds 1
} else {
# For PowerShell Desktop, use .NET Ping class with timeout
$ping = New-Object System.Net.NetworkInformation.Ping
$result = $ping.Send("github.com", 1000) # 1 second timeout
return ($result.Status -eq "Success")
}
}
$global:canConnectToGitHub = Test-GitHubConnection
# Import Modules and External Profiles
# Ensure Terminal-Icons module is installed before importing
if (-not (Get-Module -ListAvailable -Name Terminal-Icons)) {
Install-Module -Name Terminal-Icons -Scope CurrentUser -Force -SkipPublisherCheck
}
Import-Module -Name Terminal-Icons
$ChocolateyProfile = "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1"
if (Test-Path($ChocolateyProfile)) {
Import-Module "$ChocolateyProfile"
}
# Safely read and parse the last execution date once to avoid exceptions when the file is missing or empty
$lastExecRaw = if (Test-Path $timeFilePath) { (Get-Content -Path $timeFilePath -Raw).Trim() } else { $null }
[Nullable[datetime]]$lastExec = $null
if (-not [string]::IsNullOrWhiteSpace($lastExecRaw)) {
[datetime]$parsed = [datetime]::MinValue
if ([datetime]::TryParseExact($lastExecRaw, 'yyyy-MM-dd', $null, [System.Globalization.DateTimeStyles]::None, [ref]$parsed)) {
$lastExec = $parsed
}
}
# Check for Profile Updates
function Update-Profile {
# If function "Update-Profile_Override" is defined in profile.ps1 file
# then call it instead.
if (Get-Command -Name "Update-Profile_Override" -ErrorAction SilentlyContinue) {
Update-Profile_Override
} else {
try {
$url = "$repo_root/powershell-profile/main/Microsoft.PowerShell_profile.ps1"
$oldhash = Get-FileHash $PROFILE
Invoke-RestMethod $url -OutFile "$env:temp/Microsoft.PowerShell_profile.ps1"
$newhash = Get-FileHash "$env:temp/Microsoft.PowerShell_profile.ps1"
if ($newhash.Hash -ne $oldhash.Hash) {
Copy-Item -Path "$env:temp/Microsoft.PowerShell_profile.ps1" -Destination $PROFILE -Force
Write-Host "Profile has been updated. Please restart your shell to reflect changes" -ForegroundColor Magenta
} else {
Write-Host "Profile is up to date." -ForegroundColor Green
}
} catch {
Write-Error "Unable to check for `$profile updates: $_"
} finally {
Remove-Item "$env:temp/Microsoft.PowerShell_profile.ps1" -ErrorAction SilentlyContinue
}
}
}
# Check if not in debug mode AND (updateInterval is -1 OR file doesn't exist OR time difference is greater than the update interval)
if (-not $debug -and `
($updateInterval -eq -1 -or `
-not (Test-Path $timeFilePath) -or `
$null -eq $lastExec -or `
((Get-Date) - $lastExec).TotalDays -gt $updateInterval)) {
Update-Profile
$currentTime = Get-Date -Format 'yyyy-MM-dd'
$currentTime | Out-File -FilePath $timeFilePath
} elseif ($debug) {
Write-Warning "Skipping profile update check in debug mode"
}
function Update-PowerShell {
# If function "Update-PowerShell_Override" is defined in profile.ps1 file
# then call it instead.
if (Get-Command -Name "Update-PowerShell_Override" -ErrorAction SilentlyContinue) {
Update-PowerShell_Override
} else {
try {
Write-Host "Checking for PowerShell updates..." -ForegroundColor Cyan
$updateNeeded = $false
$currentVersion = $PSVersionTable.PSVersion.ToString()
$gitHubApiUrl = "https://api.github.com/repos/PowerShell/PowerShell/releases/latest"
$latestReleaseInfo = Invoke-RestMethod -Uri $gitHubApiUrl
$latestVersion = $latestReleaseInfo.tag_name.Trim('v')
if ($currentVersion -lt $latestVersion) {
$updateNeeded = $true
}
if ($updateNeeded) {
Write-Host "Updating PowerShell..." -ForegroundColor Yellow
Start-Process powershell.exe -ArgumentList "-NoProfile -Command winget upgrade Microsoft.PowerShell --accept-source-agreements --accept-package-agreements" -Wait -NoNewWindow
Write-Host "PowerShell has been updated. Please restart your shell to reflect changes" -ForegroundColor Magenta
} else {
Write-Host "Your PowerShell is up to date." -ForegroundColor Green
}
} catch {
Write-Error "Failed to update PowerShell. Error: $_"
}
}
}
# skip in debug mode
# Check if not in debug mode AND (updateInterval is -1 OR file doesn't exist OR time difference is greater than the update interval)
if (-not $debug -and `
($updateInterval -eq -1 -or `
-not (Test-Path $timeFilePath) -or `
$null -eq $lastExec -or `
((Get-Date).Date - $lastExec.Date).TotalDays -gt $updateInterval)) {
Update-PowerShell
$currentTime = Get-Date -Format 'yyyy-MM-dd'
$currentTime | Out-File -FilePath $timeFilePath
} elseif ($debug) {
Write-Warning "Skipping PowerShell update in debug mode"
}
function Clear-Cache {
# If function "Clear-Cache_Override" is defined in profile.ps1 file
# then call it instead.
# -----------------------------------------------------------------
# If you do override this function, you should should probably duplicate
# the following calls in your override function, just don't call this
# function from your override function, otherwise you'll be in an infinate loop.
if (Get-Command -Name "Clear-Cache_Override" -ErrorAction SilentlyContinue) {
Clear-Cache_Override
} else {
# add clear cache logic here
Write-Host "Clearing cache..." -ForegroundColor Cyan
# Clear Windows Prefetch
Write-Host "Clearing Windows Prefetch..." -ForegroundColor Yellow
Remove-Item -Path "$env:SystemRoot\Prefetch\*" -Force -ErrorAction SilentlyContinue
# Clear Windows Temp
Write-Host "Clearing Windows Temp..." -ForegroundColor Yellow
Remove-Item -Path "$env:SystemRoot\Temp\*" -Recurse -Force -ErrorAction SilentlyContinue
# Clear User Temp
Write-Host "Clearing User Temp..." -ForegroundColor Yellow
Remove-Item -Path "$env:TEMP\*" -Recurse -Force -ErrorAction SilentlyContinue
# Clear Internet Explorer Cache
Write-Host "Clearing Internet Explorer Cache..." -ForegroundColor Yellow
Remove-Item -Path "$env:LOCALAPPDATA\Microsoft\Windows\INetCache\*" -Recurse -Force -ErrorAction SilentlyContinue
Write-Host "Cache clearing completed." -ForegroundColor Green
}
}
# Admin Check and Prompt Customization
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
function prompt {
if ($isAdmin) { "[" + (Get-Location) + "] # " } else { "[" + (Get-Location) + "] $ " }
}
$adminSuffix = if ($isAdmin) { " [ADMIN]" } else { "" }
$Host.UI.RawUI.WindowTitle = "PowerShell {0}$adminSuffix" -f $PSVersionTable.PSVersion.ToString()
# Utility Functions
function Test-CommandExists {
param($command)
$exists = $null -ne (Get-Command $command -ErrorAction SilentlyContinue)
return $exists
}
# Editor Configuration
if ($EDITOR_Override){
$EDITOR = $EDITOR_Override
} else {
$EDITOR = if (Test-CommandExists nvim) { 'nvim' }
elseif (Test-CommandExists pvim) { 'pvim' }
elseif (Test-CommandExists vim) { 'vim' }
elseif (Test-CommandExists vi) { 'vi' }
elseif (Test-CommandExists code) { 'code' }
elseif (Test-CommandExists codium) { 'codium' }
elseif (Test-CommandExists notepad++) { 'notepad++' }
elseif (Test-CommandExists sublime_text) { 'sublime_text' }
else { 'notepad' }
Set-Alias -Name vim -Value $EDITOR
}
# Quick Access to Editing the Profile
function Edit-Profile {
& $EDITOR $PROFILE.CurrentUserAllHosts
}
Set-Alias -Name ep -Value Edit-Profile
function Invoke-Profile {
if ($PSVersionTable.PSEdition -eq "Desktop") {
Write-Host "Note: Some Oh My Posh/PSReadLine errors are expected in PowerShell 5. The profile still works fine." -ForegroundColor Yellow
}
& $PROFILE
}
function touch($file) { "" | Out-File $file -Encoding ASCII }
function ff($name) {
Get-ChildItem -recurse -filter "*${name}*" -ErrorAction SilentlyContinue | ForEach-Object {
Write-Output "$($_.FullName)"
}
}
# Network Utilities
function pubip { (Invoke-WebRequest http://ifconfig.me/ip).Content }
# Open WinUtil full-release
function winutil {
Invoke-Expression (Invoke-RestMethod https://christitus.com/win)
}
# Open WinUtil dev-release
function winutildev {
# If function "WinUtilDev_Override" is defined in profile.ps1 file
# then call it instead.
if (Get-Command -Name "WinUtilDev_Override" -ErrorAction SilentlyContinue) {
WinUtilDev_Override
} else {
Invoke-Expression (Invoke-RestMethod https://christitus.com/windev)
}
}
# System Utilities
function admin {
$cwd = (Get-Location).ProviderPath
if ($args.Count -gt 0) {
$argList = $args -join ' '
Start-Process wt -Verb runAs -ArgumentList @('-d', $cwd, 'pwsh.exe', '-NoExit', '-Command', $argList)
} else {
Start-Process wt -Verb runAs -ArgumentList @('-d', $cwd, 'pwsh.exe', '-NoExit')
}
}
# Set UNIX-like aliases for the admin command, so sudo <command> will run the command with elevated rights.
Set-Alias -Name su -Value admin
function uptime {
try {
# find date/time format
$dateFormat = [System.Globalization.CultureInfo]::CurrentCulture.DateTimeFormat.ShortDatePattern
$timeFormat = [System.Globalization.CultureInfo]::CurrentCulture.DateTimeFormat.LongTimePattern
# check powershell version
if ($PSVersionTable.PSVersion.Major -eq 5) {
$lastBoot = (Get-WmiObject win32_operatingsystem).LastBootUpTime
$bootTime = [System.Management.ManagementDateTimeConverter]::ToDateTime($lastBoot)
# reformat lastBoot
$lastBoot = $bootTime.ToString("$dateFormat $timeFormat")
} else {
# the Get-Uptime cmdlet was introduced in PowerShell 6.0
$lastBoot = (Get-Uptime -Since).ToString("$dateFormat $timeFormat")
$bootTime = [System.DateTime]::ParseExact($lastBoot, "$dateFormat $timeFormat", [System.Globalization.CultureInfo]::InvariantCulture)
}
# Format the start time
$formattedBootTime = $bootTime.ToString("dddd, MMMM dd, yyyy HH:mm:ss", [System.Globalization.CultureInfo]::InvariantCulture) + " [$lastBoot]"
Write-Host "System started on: $formattedBootTime" -ForegroundColor DarkGray
# calculate uptime
$uptime = (Get-Date) - $bootTime
# Uptime in days, hours, minutes, and seconds
$days = $uptime.Days
$hours = $uptime.Hours
$minutes = $uptime.Minutes
$seconds = $uptime.Seconds
# Uptime output
Write-Host ("Uptime: {0} days, {1} hours, {2} minutes, {3} seconds" -f $days, $hours, $minutes, $seconds) -ForegroundColor Blue
} catch {
Write-Error "An error occurred while retrieving system uptime."
}
}
function unzip ($file) {
Write-Output("Extracting", $file, "to", $pwd)
$fullFile = Get-ChildItem -Path $pwd -Filter $file | ForEach-Object { $_.FullName }
Expand-Archive -Path $fullFile -DestinationPath $pwd
}
function hb {
if ($args.Length -eq 0) {
Write-Error "No file path specified."
return
}
$FilePath = $args[0]
if (Test-Path $FilePath) {
$Content = Get-Content $FilePath -Raw
} else {
Write-Error "File path does not exist."
return
}
$uri = "http://bin.christitus.com/documents"
try {
$response = Invoke-RestMethod -Uri $uri -Method Post -Body $Content -ErrorAction Stop
$hasteKey = $response.key
$url = "http://bin.christitus.com/$hasteKey"
Set-Clipboard $url
Write-Output "$url copied to clipboard."
} catch {
Write-Error "Failed to upload the document. Error: $_"
}
}
function grep($regex, $dir) {
if ( $dir ) {
Get-ChildItem $dir | select-string $regex
return
}
$input | select-string $regex
}
function df {
get-volume
}
function sed($file, $find, $replace) {
(Get-Content $file).replace("$find", $replace) | Set-Content $file
}
function which($name) {
Get-Command $name | Select-Object -ExpandProperty Definition
}
function export($name, $value) {
set-item -force -path "env:$name" -value $value;
}
function pkill($name) {
Get-Process $name -ErrorAction SilentlyContinue | Stop-Process
}
function pgrep($name) {
Get-Process $name
}
function head {
param($Path, $n = 10)
Get-Content $Path -Head $n
}
function tail {
param($Path, $n = 10, [switch]$f = $false)
Get-Content $Path -Tail $n -Wait:$f
}
# Quick File Creation
function nf { param($name) New-Item -ItemType "file" -Path . -Name $name }
# Directory Management
function mkcd { param($dir) mkdir $dir -Force; Set-Location $dir }
function trash($path) {
$fullPath = (Resolve-Path -Path $path).Path
if (Test-Path $fullPath) {
$item = Get-Item $fullPath
if ($item.PSIsContainer) {
# Handle directory
$parentPath = $item.Parent.FullName
} else {
# Handle file
$parentPath = $item.DirectoryName
}
$shell = New-Object -ComObject 'Shell.Application'
$shellItem = $shell.NameSpace($parentPath).ParseName($item.Name)
if ($item) {
$shellItem.InvokeVerb('delete')
Write-Host "Item '$fullPath' has been moved to the Recycle Bin."
} else {
Write-Host "Error: Could not find the item '$fullPath' to trash."
}
} else {
Write-Host "Error: Item '$fullPath' does not exist."
}
}
### Quality of Life Aliases
# Navigation Shortcuts
function docs {
$docs = if(([Environment]::GetFolderPath("MyDocuments"))) {([Environment]::GetFolderPath("MyDocuments"))} else {$HOME + "\Documents"}
Set-Location -Path $docs
}
function dtop {
$dtop = if ([Environment]::GetFolderPath("Desktop")) {[Environment]::GetFolderPath("Desktop")} else {$HOME + "\Documents"}
Set-Location -Path $dtop
}
# Simplified Process Management
function k9 { Stop-Process -Name $args[0] }
# Enhanced Listing
function la { Get-ChildItem | Format-Table -AutoSize }
function ll { Get-ChildItem -Force | Format-Table -AutoSize }
# Git Shortcuts
function gs { git status }
function ga { git add . }
function gc { param($m) git commit -m "$m" }
function gpush { git push }
function gpull { git pull }
function g { __zoxide_z github }
function gcl { git clone "$args" }
function gcom {
git add .
git commit -m "$args"
}
function lazyg {
git add .
git commit -m "$args"
git push
}
# Quick Access to System Information
function sysinfo { Get-ComputerInfo }
# Networking Utilities
function flushdns {
Clear-DnsClientCache
Write-Host "DNS has been flushed"
}
# Clipboard Utilities
function cpy { Set-Clipboard $args[0] }
function pst { Get-Clipboard }
# Set-PSReadLineOption Compatibility for PowerShell Desktop
function Set-PSReadLineOptionsCompat {
param([hashtable]$Options)
if ($PSVersionTable.PSEdition -eq "Core") {
Set-PSReadLineOption @Options
} else {
# Remove unsupported keys for Desktop and silence errors
$SafeOptions = $Options.Clone()
$SafeOptions.Remove('PredictionSource')
$SafeOptions.Remove('PredictionViewStyle')
Set-PSReadLineOption @SafeOptions
}
}
# Enhanced PowerShell Experience
# Enhanced PSReadLine Configuration
$PSReadLineOptions = @{
EditMode = 'Windows'
HistoryNoDuplicates = $true
HistorySearchCursorMovesToEnd = $true
Colors = @{
Command = '#87CEEB' # SkyBlue (pastel)
Parameter = '#98FB98' # PaleGreen (pastel)
Operator = '#FFB6C1' # LightPink (pastel)
Variable = '#DDA0DD' # Plum (pastel)
String = '#FFDAB9' # PeachPuff (pastel)
Number = '#B0E0E6' # PowderBlue (pastel)
Type = '#F0E68C' # Khaki (pastel)
Comment = '#D3D3D3' # LightGray (pastel)
Keyword = '#8367c7' # Violet (pastel)
Error = '#FF6347' # Tomato (keeping it close to red for visibility)
}
PredictionSource = 'History'
PredictionViewStyle = 'ListView'
BellStyle = 'None'
}
Set-PSReadLineOptionsCompat -Options $PSReadLineOptions
# Custom key handlers
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
# Custom functions for PSReadLine
Set-PSReadLineOption -AddToHistoryHandler {
param($line)
$sensitive = @('password', 'secret', 'token', 'apikey', 'connectionstring')
$hasSensitive = $sensitive | Where-Object { $line -match $_ }
return ($null -eq $hasSensitive)
}
# Fix Set-PredictionSource for Desktop
function Set-PredictionSource {
# If "Set-PredictionSource_Override" is defined in profile.ps1 file
# then call it instead.
if (Get-Command -Name "Set-PredictionSource_Override" -ErrorAction SilentlyContinue) {
Set-PredictionSource_Override
} elseif ($PSVersionTable.PSEdition -eq "Core") {
# Improved prediction settings
Set-PSReadLineOption -PredictionSource HistoryAndPlugin
Set-PSReadLineOption -MaximumHistoryCount 10000
} else {
# Desktop version - use History only
Set-PSReadLineOption -MaximumHistoryCount 10000
}
}
Set-PredictionSource
# Custom completion for common commands
$scriptblock = {
param($wordToComplete, $commandAst, $cursorPosition)
$customCompletions = @{
'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')
}
$command = $commandAst.CommandElements[0].Value
if ($customCompletions.ContainsKey($command)) {
$customCompletions[$command] | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
}
}
}
Register-ArgumentCompleter -Native -CommandName git, npm, deno -ScriptBlock $scriptblock
$scriptblock = {
param($wordToComplete, $commandAst, $cursorPosition)
dotnet complete --position $cursorPosition $commandAst.ToString() |
ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
}
}
Register-ArgumentCompleter -Native -CommandName dotnet -ScriptBlock $scriptblock
# If function "Get-Theme_Override" is defined in profile.ps1 file
# then call it instead.
if (Get-Command -Name "Get-Theme_Override" -ErrorAction SilentlyContinue) {
Get-Theme_Override
} else {
# Oh My Posh initialization with local theme fallback and auto-download
$localThemePath = Join-Path (Get-ProfileDir) "cobalt2.omp.json"
if (-not (Test-Path $localThemePath)) {
# Try to download the theme file to the detected local path
$themeUrl = "https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/cobalt2.omp.json"
try {
Invoke-RestMethod -Uri $themeUrl -OutFile $localThemePath
Write-Host "Downloaded missing Oh My Posh theme to $localThemePath"
} catch {
Write-Warning "Failed to download theme file. Falling back to remote theme. Error: $_"
}
}
if (Test-Path $localThemePath) {
oh-my-posh init pwsh --config $localThemePath | Invoke-Expression
} else {
# Fallback to remote theme if local file doesn't exist
oh-my-posh init pwsh --config https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/cobalt2.omp.json | Invoke-Expression
}
}
if (Get-Command zoxide -ErrorAction SilentlyContinue) {
Invoke-Expression (& { (zoxide init --cmd z powershell | Out-String) })
} else {
Write-Host "zoxide command not found. Attempting to install via winget..."
try {
winget install -e --id ajeetdsouza.zoxide
Write-Host "zoxide installed successfully. Initializing..."
Invoke-Expression (& { (zoxide init --cmd z powershell | Out-String) })
} catch {
Write-Error "Failed to install zoxide. Error: $_"
}
}
# Help Function
function Show-Help {
$helpText = @"
$($PSStyle.Foreground.Cyan)PowerShell Profile Help$($PSStyle.Reset)
$($PSStyle.Foreground.Yellow)=======================$($PSStyle.Reset)
$($PSStyle.Foreground.Green)Edit-Profile$($PSStyle.Reset) - Opens the current user's profile for editing using the configured editor.
$($PSStyle.Foreground.Green)Update-Profile$($PSStyle.Reset) - Checks for profile updates from a remote repository and updates if necessary.
$($PSStyle.Foreground.Green)Update-PowerShell$($PSStyle.Reset) - Checks for the latest PowerShell release and updates if a new version is available.
$($PSStyle.Foreground.Cyan)Git Shortcuts$($PSStyle.Reset)
$($PSStyle.Foreground.Yellow)=======================$($PSStyle.Reset)
$($PSStyle.Foreground.Green)g$($PSStyle.Reset) - Changes to the GitHub directory.
$($PSStyle.Foreground.Green)ga$($PSStyle.Reset) - Shortcut for 'git add .'.
$($PSStyle.Foreground.Green)gc$($PSStyle.Reset) <message> - Shortcut for 'git commit -m'.
$($PSStyle.Foreground.Green)gcl$($PSStyle.Reset) <repo> - Shortcut for 'git clone'.
$($PSStyle.Foreground.Green)gcom$($PSStyle.Reset) <message> - Adds all changes and commits with the specified message.
$($PSStyle.Foreground.Green)gp$($PSStyle.Reset) - Shortcut for 'git push'.
$($PSStyle.Foreground.Green)gpull$($PSStyle.Reset) - Shortcut for 'git pull'.
$($PSStyle.Foreground.Green)gpush$($PSStyle.Reset) - Shortcut for 'git push'.
$($PSStyle.Foreground.Green)gs$($PSStyle.Reset) - Shortcut for 'git status'.
$($PSStyle.Foreground.Green)lazyg$($PSStyle.Reset) <message> - Adds all changes, commits with the specified message, and pushes to the remote repository.
$($PSStyle.Foreground.Cyan)Shortcuts$($PSStyle.Reset)
$($PSStyle.Foreground.Yellow)=======================$($PSStyle.Reset)
$($PSStyle.Foreground.Green)cpy$($PSStyle.Reset) <text> - Copies the specified text to the clipboard.
$($PSStyle.Foreground.Green)df$($PSStyle.Reset) - Displays information about volumes.
$($PSStyle.Foreground.Green)docs$($PSStyle.Reset) - Changes the current directory to the user's Documents folder.
$($PSStyle.Foreground.Green)dtop$($PSStyle.Reset) - Changes the current directory to the user's Desktop folder.
$($PSStyle.Foreground.Green)ep$($PSStyle.Reset) - Opens the profile for editing.
$($PSStyle.Foreground.Green)export$($PSStyle.Reset) <name> <value> - Sets an environment variable.
$($PSStyle.Foreground.Green)ff$($PSStyle.Reset) <name> - Finds files recursively with the specified name.
$($PSStyle.Foreground.Green)flushdns$($PSStyle.Reset) - Clears the DNS cache.
$($PSStyle.Foreground.Green)pubip$($PSStyle.Reset) - Retrieves the public IP address of the machine.
$($PSStyle.Foreground.Green)grep$($PSStyle.Reset) <regex> [dir] - Searches for a regex pattern in files within the specified directory or from the pipeline input.
$($PSStyle.Foreground.Green)hb$($PSStyle.Reset) <file> - Uploads the specified file's content to a hastebin-like service and returns the URL.
$($PSStyle.Foreground.Green)head$($PSStyle.Reset) <path> [n] - Displays the first n lines of a file (default 10).
$($PSStyle.Foreground.Green)k9$($PSStyle.Reset) <name> - Kills a process by name.
$($PSStyle.Foreground.Green)la$($PSStyle.Reset) - Lists all files in the current directory with detailed formatting.
$($PSStyle.Foreground.Green)ll$($PSStyle.Reset) - Lists all files, including hidden, in the current directory with detailed formatting.
$($PSStyle.Foreground.Green)mkcd$($PSStyle.Reset) <dir> - Creates and changes to a new directory.
$($PSStyle.Foreground.Green)nf$($PSStyle.Reset) <name> - Creates a new file with the specified name.
$($PSStyle.Foreground.Green)pgrep$($PSStyle.Reset) <name> - Lists processes by name.
$($PSStyle.Foreground.Green)pkill$($PSStyle.Reset) <name> - Kills processes by name.
$($PSStyle.Foreground.Green)pst$($PSStyle.Reset) - Retrieves text from the clipboard.
$($PSStyle.Foreground.Green)sed$($PSStyle.Reset) <file> <find> <replace> - Replaces text in a file.
$($PSStyle.Foreground.Green)sysinfo$($PSStyle.Reset) - Displays detailed system information.
$($PSStyle.Foreground.Green)tail$($PSStyle.Reset) <path> [n] - Displays the last n lines of a file (default 10).
$($PSStyle.Foreground.Green)touch$($PSStyle.Reset) <file> - Creates a new empty file.
$($PSStyle.Foreground.Green)unzip$($PSStyle.Reset) <file> - Extracts a zip file to the current directory.
$($PSStyle.Foreground.Green)uptime$($PSStyle.Reset) - Displays the system uptime.
$($PSStyle.Foreground.Green)which$($PSStyle.Reset) <name> - Shows the path of the command.
$($PSStyle.Foreground.Green)winutil$($PSStyle.Reset) - Runs the latest WinUtil full-release script from Chris Titus Tech.
$($PSStyle.Foreground.Green)winutildev$($PSStyle.Reset) - Runs the latest WinUtil pre-release script from Chris Titus Tech.
$($PSStyle.Foreground.Yellow)=======================$($PSStyle.Reset)
Use '$($PSStyle.Foreground.Magenta)Show-Help$($PSStyle.Reset)' to display this help message.
"@
Write-Host $helpText
}
if (Test-Path "$PSScriptRoot\CTTcustom.ps1") {
. (Join-Path -Path $PSScriptRoot -ChildPath 'CTTcustom.ps1')
}
Write-Host "$($PSStyle.Foreground.Yellow)Use 'Show-Help' to display help$($PSStyle.Reset)"