-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMicrosoft.PowerShell_profile.ps1
More file actions
905 lines (797 loc) · 41.7 KB
/
Microsoft.PowerShell_profile.ps1
File metadata and controls
905 lines (797 loc) · 41.7 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
# Ensure we are running on Windows
if ($PSVersionTable.PSVersion.Major -ge 6 -and -not $IsWindows) { return }
# --- Shell Initialization ---
# Shows navigable menu of all options when hitting Tab
Set-PSReadlineKeyHandler -Key Tab -Function MenuComplete
if ($PSVersionTable.PSVersion.Major -ge 6 -and ($env:WT_SESSION -or $env:TERM_PROGRAM -eq 'vscode')) {
$ompCmd = Get-Command oh-my-posh -ErrorAction SilentlyContinue
if (-not $ompCmd) {
Write-Host "Oh My Posh not found. Installing..." -ForegroundColor Yellow
winget install JanDeDobbeleer.OhMyPosh -s winget --accept-source-agreements --accept-package-agreements
$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
$ompCmd = Get-Command oh-my-posh -ErrorAction SilentlyContinue
}
if ($ompCmd) {
$themeDir = "$env:LOCALAPPDATA\oh-my-posh\themes"
if ($env:POSH_THEMES_PATH) { $themeDir = $env:POSH_THEMES_PATH }
if (-not (Test-Path $themeDir)) { $null = New-Item -ItemType Directory -Path $themeDir -Force }
$themeConfig = "$env:LOCALAPPDATA\oh-my-posh\selected_theme.txt"
$themeName = if (Test-Path $themeConfig) { Get-Content $themeConfig -Raw | ForEach-Object { $_.Trim() } } else { "blue-owl.omp.json" }
$themePath = Join-Path $themeDir $themeName
if (-not (Test-Path $themePath) -and $themeName -eq "blue-owl.omp.json") {
$themeUrl = "https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/blue-owl.omp.json"
Write-Host "Downloading Oh My Posh theme ($themeName)..." -ForegroundColor Yellow
try { Invoke-WebRequest $themeUrl -OutFile $themePath } catch {}
}
# Cache the init script; only regenerate when oh-my-posh is updated or theme changes
# This significantly improves startup time by avoiding the 'oh-my-posh init' command overhead on every shell launch.
$ompInitScript = "$env:TEMP\omp_init.ps1"
$shouldUpdate = -not (Test-Path $ompInitScript)
if (-not $shouldUpdate -and $ompCmd.Source -and [System.IO.File]::GetLastWriteTime($ompCmd.Source) -gt [System.IO.File]::GetLastWriteTime($ompInitScript)) { $shouldUpdate = $true }
if (-not $shouldUpdate -and (Test-Path $themeConfig) -and [System.IO.File]::GetLastWriteTime($themeConfig) -gt [System.IO.File]::GetLastWriteTime($ompInitScript)) { $shouldUpdate = $true }
if ($shouldUpdate -and (Test-Path $themePath)) {
oh-my-posh init pwsh --config $themePath | Set-Content $ompInitScript -Encoding UTF8
}
if (Test-Path $ompInitScript) { . $ompInitScript }
}
}
# Select Oh My Posh theme from GitHub
function global:Set-PoshTheme {
$themeDir = "$env:LOCALAPPDATA\oh-my-posh\themes"
if ($env:POSH_THEMES_PATH) { $themeDir = $env:POSH_THEMES_PATH }
if (-not (Test-Path $themeDir)) { $null = New-Item -ItemType Directory -Path $themeDir -Force }
Write-Host "Fetching themes from GitHub API..." -ForegroundColor Yellow
try {
$themes = Invoke-RestMethod "https://api.github.com/repos/JanDeDobbeleer/oh-my-posh/contents/themes" -ErrorAction Stop |
Where-Object { $_.name -like "*.omp.json" }
} catch {
Write-Error "Failed to fetch themes: $_"
return
}
# Prefer Out-ConsoleGridView (TUI) over Out-GridView (GUI)
if (-not (Get-Command Out-ConsoleGridView -ErrorAction SilentlyContinue)) {
if ($Host.UI.PromptForChoice("Install TUI?", "Install 'Microsoft.PowerShell.ConsoleGuiTools' for a better terminal-based menu?", ('&Yes', '&No'), 1) -eq 0) {
Install-Module Microsoft.PowerShell.ConsoleGuiTools -Scope CurrentUser -Force -AllowClobber
Import-Module Microsoft.PowerShell.ConsoleGuiTools -ErrorAction SilentlyContinue
}
}
$list = $themes | Select-Object -Property name, download_url | Sort-Object name
if (Get-Command Out-ConsoleGridView -ErrorAction SilentlyContinue) {
$selected = $list | Out-ConsoleGridView -Title "Select Oh My Posh Theme (GitHub)" -OutputMode Single
} else {
$selected = $list | Out-GridView -Title "Select Oh My Posh Theme (GitHub)" -OutputMode Single
}
if ($selected) {
$themeName = $selected.name
$themePath = Join-Path $themeDir $themeName
if (Test-Path $themePath) { Remove-Item $themePath -Force }
Write-Host "Downloading $themeName..." -ForegroundColor Yellow
Invoke-WebRequest $selected.download_url -OutFile $themePath -UseBasicParsing
$themeConfig = "$env:LOCALAPPDATA\oh-my-posh\selected_theme.txt"
$themeName | Set-Content $themeConfig -Force
Write-Host "Theme set to '$themeName'. Reloading..." -ForegroundColor Green
Import-Profile
}
}
Set-Alias theme Set-PoshTheme -Scope Global
# Rotate through Oh My Posh themes (Slideshow)
function global:Show-PoshThemeSlideshow {
param(
[switch]$Random,
[int]$Seconds = 3
)
$themeDir = "$env:LOCALAPPDATA\oh-my-posh\themes"
if ($env:POSH_THEMES_PATH) { $themeDir = $env:POSH_THEMES_PATH }
if (-not (Test-Path $themeDir)) { $null = New-Item -ItemType Directory -Path $themeDir -Force }
Write-Host "Fetching themes from GitHub API..." -ForegroundColor Yellow
try {
$themes = Invoke-RestMethod "https://api.github.com/repos/JanDeDobbeleer/oh-my-posh/contents/themes" -ErrorAction Stop |
Where-Object { $_.name -like "*.omp.json" }
if ($Random) {
$themes = $themes | Sort-Object { Get-Random }
} else {
$themes = $themes | Sort-Object name
}
} catch {
Write-Error "Failed to fetch themes: $_"
return
}
Write-Host "Starting slideshow. Controls: [<-] Prev | [->] Next | [Enter] Select | [Esc] Cancel" -ForegroundColor Cyan
Start-Sleep -Seconds 1
$index = 0
while ($true) {
if ($index -ge $themes.Count) { $index = 0 }
if ($index -lt 0) { $index = $themes.Count - 1 }
$theme = $themes[$index]
$themeName = $theme.name
$themePath = Join-Path $themeDir $themeName
# Download if missing (skip re-downloading existing files for speed)
if (-not (Test-Path $themePath)) {
Write-Host "Downloading $themeName..." -ForegroundColor DarkGray
try { Invoke-WebRequest $theme.download_url -OutFile $themePath -UseBasicParsing } catch { continue }
}
# Apply theme temporarily
try { oh-my-posh init pwsh --config $themePath | Invoke-Expression } catch { continue }
Clear-Host
$prevName = if ($index -gt 0) { $themes[$index - 1].name } else { $themes[-1].name }
$nextName = if ($index -lt $themes.Count - 1) { $themes[$index + 1].name } else { $themes[0].name }
Write-Host "Previous: $prevName" -ForegroundColor DarkGray
Write-Host "Current: $themeName" -ForegroundColor Yellow
Write-Host "Next: $nextName" -ForegroundColor DarkGray
Write-Host "Controls: [<-] Prev | [->] Next | [Enter] Select | [Esc] Cancel" -ForegroundColor Cyan
Write-Host ""
# Render the prompt to preview it
prompt
# Wait loop
$manualNav = $false
$iterations = $Seconds * 10
for ($i = 0; $i -lt $iterations; $i++) {
if ([Console]::KeyAvailable) {
$key = [Console]::ReadKey($true)
if ($key.Key -eq 'Enter') {
$themeConfig = "$env:LOCALAPPDATA\oh-my-posh\selected_theme.txt"
$themeName | Set-Content $themeConfig -Force
Write-Host "`nSelected '$themeName'. Reloading..." -ForegroundColor Green
Import-Profile
return
} elseif ($key.Key -eq 'Escape' -or $key.KeyChar -eq 'q') {
Write-Host "`nCancelled. Reverting..." -ForegroundColor Yellow
Import-Profile
return
} elseif ($key.Key -eq 'LeftArrow' -or $key.KeyChar -eq 'p') {
$index--
$manualNav = $true
break
} elseif ($key.Key -eq 'RightArrow' -or $key.KeyChar -eq 'n') {
$index++
$manualNav = $true
break
}
}
Start-Sleep -Milliseconds 100
}
if (-not $manualNav) { $index++ }
}
}
Set-Alias slideshow Show-PoshThemeSlideshow -Scope Global
# Enable Predictive IntelliSense (History based)
try {
Set-PSReadLineOption -PredictionSource History
Set-PSReadLineOption -PredictionViewStyle ListView
} catch {}
# --- Navigation ---
# Quick Navigation
function global:.. { Set-Location .. }
function global:... { Set-Location ..\.. }
# Create directory and enter it
function global:New-DirectoryAndEnter {
param([Parameter(Mandatory)][string]$Path)
$null = New-Item -ItemType Directory -Path $Path -Force
Set-Location $Path
}
# Define alias in Global scope so it persists after profile script finishes
Set-Alias mk New-DirectoryAndEnter -Scope Global
# --- File Operations ---
# List files (force)
function global:Get-ChildItemForce { Get-ChildItem -Force @args }
Set-Alias ll Get-ChildItemForce -Scope Global
# Create new file or update timestamp
function global:Update-FileTimestamp {
param([Parameter(Mandatory)][string]$Path)
if (Test-Path $Path) {
(Get-Item $Path).LastWriteTime = Get-Date
} else {
$null = New-Item -ItemType File -Path $Path -Force
}
}
Set-Alias touch Update-FileTimestamp -Scope Global
# Find file recursively
function global:Find-File {
param([Parameter(Mandatory)][string]$Name)
Get-ChildItem -Recurse -Filter "*$Name*" -ErrorAction SilentlyContinue
}
Set-Alias ff Find-File -Scope Global
# Extract zip file
function global:Expand-ArchiveFile {
param([Parameter(Mandatory)][string]$Path, [string]$Destination = ".")
Expand-Archive -Path $Path -DestinationPath $Destination -Force
}
Set-Alias unzip Expand-ArchiveFile -Scope Global
# --- System Utilities ---
# Refresh Path environment variable from registry
# Reloads PATH from the Registry (Machine and User scopes) so changes (like new installs) take effect immediately
# without restarting the PowerShell session.
function global:Update-EnvironmentPath {
$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
Write-Host "Path environment variables reloaded." -ForegroundColor Green
}
Set-Alias Refresh-Path Update-EnvironmentPath -Scope Global
# Run as Administrator
function global:Invoke-ElevatedCommand {
# Install gsudo (sudo for Windows) if not found
if (-not (Get-Command gsudo -ErrorAction SilentlyContinue)) {
Write-Host "gsudo not found. Installing..." -ForegroundColor Yellow
winget install gerardog.gsudo -s winget --accept-source-agreements --accept-package-agreements
Update-EnvironmentPath
}
gsudo --loadProfile @args
}
Set-Alias sudo Invoke-ElevatedCommand -Scope Global
# Upgrade all software via winget
function global:Update-WindowsPackages {
try {
Invoke-ElevatedCommand {
Write-Host 'Checking WinGet packages...' -ForegroundColor Yellow
$upgradeResult = winget upgrade --include-unknown --accept-source-agreements 2>&1 | Out-String
if ($upgradeResult -notmatch "No installed package found matching input criteria.") {
winget upgrade --all --include-unknown --accept-source-agreements --accept-package-agreements
}
if (Get-CimInstance Win32_VideoController | Where-Object { $_.Name -match 'NVIDIA' }) {
Write-Host 'Checking NVIDIA drivers...' -ForegroundColor Yellow
if (-not (Get-Command TinyNvidiaUpdateChecker -ErrorAction SilentlyContinue)) {
Write-Host "TinyNvidiaUpdateChecker not found. Installing..." -ForegroundColor Yellow
winget install Hawaii_Beach.TinyNvidiaUpdateChecker -s winget --accept-source-agreements --accept-package-agreements
$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
}
if (Get-Command TinyNvidiaUpdateChecker -ErrorAction SilentlyContinue) {
TinyNvidiaUpdateChecker --quiet --confirm-dl --noprompt
}
}
Write-Host 'Checking PowerShell modules (User Scope)...' -ForegroundColor Yellow
$modules = @(Get-InstalledModule -ErrorAction SilentlyContinue | Where-Object { $_.InstalledLocation -like "$env:USERPROFILE*" })
$i = 0
$modules | ForEach-Object {
$i++
$moduleName = $_.Name
$currentVersion = $_.Version
Write-Progress -Activity "Updating Modules" -Status "Checking $moduleName" -PercentComplete (($i / $modules.Count) * 100)
try {
$result = Update-Module -Name $moduleName -Confirm:$false -ErrorAction Stop -WarningAction Stop -PassThru
if ($result -and $result.Version -ne $currentVersion) { Write-Host "Updated $moduleName to version $($result.Version)" -ForegroundColor Green }
}
catch {
Write-Host "Update failed for $moduleName. Renaming old folders..." -ForegroundColor Red
$paths = (Get-Module -ListAvailable -Name $moduleName -ErrorAction SilentlyContinue).ModuleBase
if ($paths) {
foreach ($p in $paths) {
try { Rename-Item -Path $p -NewName "$p.old_$(Get-Random)" -Force -ErrorAction SilentlyContinue } catch {}
}
}
Write-Host " Reinstalling..." -ForegroundColor Magenta
Uninstall-Module -Name $moduleName -AllVersions -Force -ErrorAction SilentlyContinue
Install-Module -Name $moduleName -Scope CurrentUser -Force -AllowClobber -ErrorAction SilentlyContinue
}
}
Write-Progress -Activity "Updating Modules" -Completed
Write-Host 'Checking Windows Update packages...' -ForegroundColor Yellow
if (-not (Get-Module -ListAvailable PSWindowsUpdate)) {
Write-Host 'Installing PSWindowsUpdate module...' -ForegroundColor Yellow
Install-Module PSWindowsUpdate -Scope CurrentUser -Force -AllowClobber -ErrorAction SilentlyContinue
}
if (Get-Module -ListAvailable PSWindowsUpdate) {
Import-Module PSWindowsUpdate
Get-WindowsUpdate -AcceptAll -Install -IgnoreReboot
}
Update-EnvironmentPath
}
}
catch {
Write-Error "Unable to update packages: $_"
}
}
Set-Alias up Update-WindowsPackages -Scope Global
# Kill process on port
function global:Stop-PortProcess {
param([int]$Port)
$tcp = Get-NetTCPConnection -LocalPort $Port -ErrorAction SilentlyContinue
if ($tcp) {
$proc = Get-Process -Id $tcp.OwningProcess -ErrorAction SilentlyContinue
if ($proc) {
Stop-Process -Id $tcp.OwningProcess -Force
Write-Host "Killed process $($proc.ProcessName) (PID: $($tcp.OwningProcess)) on port $Port" -ForegroundColor Green
} else {
Write-Host "Found PID $($tcp.OwningProcess) on port $Port, but could not access process (try sudo)." -ForegroundColor Red
}
} else {
Write-Host "No process found listening on port $Port" -ForegroundColor Yellow
}
}
if (-not (Test-Path Alias:kill-port)) { Set-Alias kill-port Stop-PortProcess -Scope Global }
# Disk Cleanup
function global:Start-SystemCleanup {
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
if (-not $isAdmin) {
Write-Host "Note: Run as Administrator (sudo cleanup) to clean system files and Component Store." -ForegroundColor Magenta
}
Write-Host "Emptying Recycle Bin..." -ForegroundColor Yellow
Clear-RecycleBin -Force -ErrorAction SilentlyContinue
Write-Host "Cleaning User Temp files..." -ForegroundColor Yellow
Remove-Item -Path "$env:TEMP\*" -Recurse -Force -ErrorAction SilentlyContinue
if ($isAdmin) {
Write-Host "Cleaning Windows Temp files..." -ForegroundColor Yellow
Remove-Item -Path "$env:windir\Temp\*" -Recurse -Force -ErrorAction SilentlyContinue
Write-Host "Cleaning Component Store (DISM)... This will take some time." -ForegroundColor Yellow
DISM.exe /Online /Cleanup-Image /StartComponentCleanup /ResetBase
}
Write-Host "Launching Disk Cleanup utility..." -ForegroundColor Green
Start-Process cleanmgr.exe -ArgumentList "/d $env:SystemDrive"
}
Set-Alias cleanup Start-SystemCleanup -Scope Global
# Reboot the computer
function global:Invoke-RebootCountdown {
Write-Host "Rebooting in 5 seconds... Press any key to cancel." -ForegroundColor Yellow
for ($i = 5; $i -gt 0; $i--) {
Write-Host -NoNewline "$i... "
# Check for key press every 100ms to allow immediate cancellation without waiting for the full second
for ($j = 0; $j -lt 10; $j++) {
if ([Console]::KeyAvailable) {
$null = [Console]::ReadKey($true)
Write-Host "`nReboot cancelled." -ForegroundColor Green
return
}
Start-Sleep -Milliseconds 100
}
}
Write-Host "`nRebooting..." -ForegroundColor Red
Restart-Computer
}
Set-Alias reboot Invoke-RebootCountdown -Scope Global
$Global:RebootMarkerPath = "$env:TEMP\ps_scheduled_reboot.xml"
function global:Get-PendingReboot {
if (-not (Test-Path $Global:RebootMarkerPath)) { return $null }
try {
$rebootTime = Import-Clixml $Global:RebootMarkerPath
$markerTime = [System.IO.File]::GetLastWriteTime($Global:RebootMarkerPath)
$bootTime = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
# If the system boot time is earlier than the marker file, the reboot hasn't happened yet.
# If boot time is later, the reboot occurred, so we fall through to cleanup.
if ($bootTime -lt $markerTime -and $rebootTime -gt (Get-Date)) {
return $rebootTime
}
} catch {}
# Cleanup marker if reboot happened or file is invalid
Remove-Item $Global:RebootMarkerPath -Force -ErrorAction SilentlyContinue
return $null
}
# Schedule a timed reboot
function global:Register-ScheduledReboot {
param([string]$Time = "3AM")
try {
$target = Get-Date $Time
if ($target -lt (Get-Date)) { $target = $target.AddDays(1) }
$seconds = [int]($target - (Get-Date)).TotalSeconds
shutdown.exe /r /t $seconds
$target | Export-Clixml -Path $Global:RebootMarkerPath -Force
Write-Host "Reboot scheduled for $($target.ToString())" -ForegroundColor Yellow
} catch {
Write-Error "Invalid time format (try '2AM', '16:30') or error scheduling."
}
}
Set-Alias treboot Register-ScheduledReboot -Scope Global
# Abort scheduled reboot
function global:Unregister-ScheduledReboot {
shutdown.exe /a
if (Test-Path $Global:RebootMarkerPath) {
Remove-Item $Global:RebootMarkerPath -Force
}
Write-Host "Scheduled reboot cancelled." -ForegroundColor Green
}
Set-Alias areboot Unregister-ScheduledReboot -Scope Global
# Lock the computer and turn off monitors
function global:Invoke-LockWorkstation {
Write-Host "Locking in 5 seconds... Press any key to cancel." -ForegroundColor Yellow
for ($i = 5; $i -gt 0; $i--) {
Write-Host -NoNewline "$i... "
# Check for key press every 100ms to allow immediate cancellation without waiting for the full second
for ($j = 0; $j -lt 10; $j++) {
if ([Console]::KeyAvailable) {
$null = [Console]::ReadKey($true)
Write-Host "`nLock cancelled." -ForegroundColor Green
return
}
Start-Sleep -Milliseconds 100
}
}
Write-Host "`nLocking..." -ForegroundColor Red
rundll32.exe user32.dll,LockWorkStation
# Use P/Invoke to send a system command to turn off the monitor.
# 0x0112 = WM_SYSCOMMAND, 0xF170 = SC_MONITORPOWER, 2 = Power Off
if (-not ([System.Management.Automation.PSTypeName]'Win32Functions.Win32PowerControl').Type) {
$null = Add-Type -MemberDefinition '[DllImport("user32.dll")] public static extern bool PostMessage(int hWnd, int hMsg, int wParam, int lParam);' -Name "Win32PowerControl" -Namespace Win32Functions
}
[void][Win32Functions.Win32PowerControl]::PostMessage(0xFFFF, 0x0112, 0xF170, 2)
}
if (-not (Test-Path Alias:l)) { Set-Alias l Invoke-LockWorkstation -Scope Global }
Set-Alias lock Invoke-LockWorkstation -Scope Global
# Clear PSReadLine History
function global:Clear-PSHistory {
$historyPath = (Get-PSReadLineOption).HistorySavePath
if (Test-Path $historyPath) {
Remove-Item $historyPath -Force
Write-Host "Persistent history deleted." -ForegroundColor Green
}
[Microsoft.PowerShell.PSConsoleReadLine]::ClearHistory()
Write-Host "In-memory history cleared." -ForegroundColor Green
}
# --- Unix Compatibility ---
if (-not (Test-Path Alias:grep)) { Set-Alias grep Select-String -Scope Global }
if (-not (Test-Path Alias:open)) { Set-Alias open Invoke-Item -Scope Global }
# Returns the file path of a command (like Unix 'which')
function global:Get-CommandSource ([string]$Name) {
Get-Command $Name -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source -First 1
}
Set-Alias which Get-CommandSource -Scope Global
function global:Convert-Base64 {
param([Parameter(ValueFromPipeline)][string]$String, [switch]$Decode)
process {
if ($Decode) {
[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($String))
} else {
[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($String))
}
}
}
Set-Alias base64 Convert-Base64 -Scope Global
function global:Get-VolumeInfo {
Get-Volume | Where-Object { $_.Size -gt 0 } | Sort-Object DriveLetter | ForEach-Object {
$size = $_.Size | Select-Object -First 1
$free = $_.SizeRemaining | Select-Object -First 1
[PSCustomObject]@{
Drive = if ($_.DriveLetter) { $_.DriveLetter + ":" } else { $_.FileSystemLabel }
'Size(GB)' = "{0:N2}" -f ($size / 1GB)
'Used(GB)' = "{0:N2}" -f (($size - $free) / 1GB)
'Free(GB)' = "{0:N2}" -f ($free / 1GB)
'%Used' = "{0:P1}" -f (1 - ($free / $size))
}
} | Format-Table -AutoSize
}
Set-Alias df Get-VolumeInfo -Scope Global
# Calculates directory size by recursively summing file lengths (can be slow on large trees)
function global:Get-DirectorySize {
param([string]$Path = ".")
$items = @(Get-ChildItem $Path -Force -ErrorAction SilentlyContinue)
if ($items.Count -eq 0) { return }
$count = $items.Count; $i = 0
$data = $items | ForEach-Object {
$i++; Write-Progress -Activity "Calculating Size" -Status "Scanning $($_.Name)" -PercentComplete (($i / $count) * 100)
$len = 0
if ($_.PSIsContainer) {
$stats = $_ | Get-ChildItem -Recurse -File -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum
if ($stats) { $len = $stats.Sum }
} else { $len = $_.Length }
[PSCustomObject]@{ Name = $_.Name; Raw = $len; Type = if ($_.PSIsContainer){"Dir"}else{"File"} }
}
Write-Progress -Activity "Calculating Size" -Completed
$total = ($data | Measure-Object Raw -Sum).Sum
$data | Sort-Object Raw -Descending | Select-Object `
@{N='Size';E={if($_.Raw -gt 1GB){"{0:N2} GB" -f ($_.Raw/1GB)}elseif($_.Raw -gt 1MB){"{0:N2} MB" -f ($_.Raw/1MB)}else{"{0:N2} KB" -f ($_.Raw/1KB)}}}, `
@{N='%Total';E={if($total -gt 0){"{0:P1}" -f ($_.Raw/$total)}else{"0%"}}}, Type, Name | Format-Table -AutoSize
Write-Host "Total: $(if($total -gt 1GB){"{0:N2} GB" -f ($total/1GB)}elseif($total -gt 1MB){"{0:N2} MB" -f ($total/1MB)}else{"{0:N2} KB" -f ($total/1KB)})" -ForegroundColor Cyan
}
Set-Alias du Get-DirectorySize -Scope Global
function global:Get-MemoryUsage {
Get-CimInstance Win32_OperatingSystem | Select-Object @{N="Total(GB)";E={"{0:N2}" -f ($_.TotalVisibleMemorySize / 1MB)}}, @{N="Free(GB)";E={"{0:N2}" -f ($_.FreePhysicalMemory / 1MB)}}
}
Set-Alias free Get-MemoryUsage -Scope Global
function global:Get-SystemUptime {
$boot = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
$uptime = (Get-Date) - $boot
$parts = @()
if ($uptime.Days -gt 0) { $parts += "$($uptime.Days)d" }
if ($uptime.Hours -gt 0) { $parts += "$($uptime.Hours)h" }
if ($uptime.Minutes -gt 0) { $parts += "$($uptime.Minutes)m" }
"Up for $(if ($parts) { $parts -join ' ' } else { "$($uptime.Seconds)s" })"
}
Set-Alias uptime Get-SystemUptime -Scope Global
function global:Get-NetworkSummary {
[CmdletBinding()]
param()
# Determine if output is being piped by checking if this command is the last in the pipeline
# This allows 'ip' to show colors in the console, but output clean text when piped (e.g., 'ip | clip')
$isPiped = $MyInvocation.PipelinePosition -lt $MyInvocation.PipelineLength
$interfaces = [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() |
Where-Object { $_.NetworkInterfaceType -ne 'Loopback' -and $_.NetworkInterfaceType -ne 'Tunnel' } |
Sort-Object { if ($_.OperationalStatus -eq 'Up') { 0 } else { 1 } }
$seenMacs = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
# This will hold our structured output objects
$outputObjects = @()
foreach ($iface in $interfaces) {
$macClean = $iface.GetPhysicalAddress().ToString()
if (-not $macClean) { continue }
$props = $iface.GetIPProperties()
$unicastV4 = $props.UnicastAddresses | Where-Object { $_.Address.AddressFamily -eq 'InterNetwork' }
if ($iface.OperationalStatus -eq 'Up' -and -not $unicastV4) { continue }
if ($seenMacs.Contains($macClean)) { continue }
$null = $seenMacs.Add($macClean)
$outputObjects += [PSCustomObject]@{ Type = 'Header'; Name = $iface.Name; Status = $iface.OperationalStatus }
$outputObjects += [PSCustomObject]@{ Type = 'Driver'; Text = " Driver: $($iface.Description)" }
$macDashed = $macClean -replace '(..)', '$1-' -replace '-$', ''
$macColon = $macClean -replace '(..)', '$1:' -replace ':$', ''
$outputObjects += [PSCustomObject]@{ Type = 'MAC'; Text = " MAC: $macDashed / $macColon / $macClean" }
if ($iface.OperationalStatus -ne 'Up') {
$outputObjects += [PSCustomObject]@{ Type = 'Info'; Text = " IPv4: Disconnected"; Color = 'Red' }
$outputObjects += [PSCustomObject]@{ Type = 'Info'; Text = " IPv6: Disconnected"; Color = 'Red' }
$outputObjects += [PSCustomObject]@{ Type = 'Info'; Text = " DNS: Disconnected"; Color = 'Red' }
} else {
$v4Str = foreach ($ip in $unicastV4) {
$mask = $ip.IPv4Mask
# Attempt reverse DNS lookup (PTR) to get hostname; use QuickTimeout to avoid UI lag
$revDns = try { (Resolve-DnsName -Name $ip.Address.IPAddressToString -Type PTR -DnsOnly -QuickTimeout -ErrorAction SilentlyContinue).NameHost } catch {}
$revDnsStr = if ($revDns -and $revDns -ne $ip.Address.IPAddressToString) { " [$($revDns.TrimEnd('.'))]" } else { "" }
if ($mask) {
$cidr = ($mask.GetAddressBytes() | ForEach-Object { [Convert]::ToString($_, 2).Replace('0', '').Length } | Measure-Object -Sum).Sum
"$($ip.Address)/$cidr ($mask)$revDnsStr"
} else {
"$($ip.Address)$revDnsStr"
}
}
$resolve = { param($ipObject)
$ipAddress = if ($ipObject -is [System.Net.IPAddress]) { $ipObject } else { $ipObject.Address }
$ipString = $ipAddress.IPAddressToString
$revDns = try { (Resolve-DnsName -Name $ipString -Type PTR -DnsOnly -QuickTimeout -ErrorAction SilentlyContinue).NameHost } catch {}
$revDnsStr = if ($revDns -and $revDns -ne $ipString) { " [$($revDns.TrimEnd('.'))]" } else { "" }
"$ipString$revDnsStr" }
$v6Str = ($props.UnicastAddresses | Where-Object { $_.Address.AddressFamily -eq 'InterNetworkV6' }) | ForEach-Object { & $resolve $_ }
$gwStr = ($props.GatewayAddresses) | ForEach-Object { & $resolve $_ }
$dnsStr = ($props.DnsAddresses) | ForEach-Object { & $resolve $_ }
$dhcp = try { if ($props.GetIPv4Properties().IsDhcpEnabled) { "DHCP" } else { "Static" } } catch { "Unknown" }
if ($v4Str) { $outputObjects += [PSCustomObject]@{ Type = 'Info'; Text = " IPv4: $($v4Str -join ', ') [$dhcp]"; Color = 'Cyan' } }
if ($v6Str) { $outputObjects += [PSCustomObject]@{ Type = 'Info'; Text = " IPv6: $($v6Str -join ', ')"; Color = 'DarkCyan' } }
if ($gwStr) { $outputObjects += [PSCustomObject]@{ Type = 'Info'; Text = " Gateway: $($gwStr -join ', ')"; Color = 'Yellow' } }
if ($dnsStr) { $outputObjects += [PSCustomObject]@{ Type = 'Info'; Text = " DNS: $($dnsStr -join ', ')"; Color = 'Green' } }
}
$outputObjects += [PSCustomObject]@{ Type = 'Blank' }
}
# Remove trailing blank line
if ($outputObjects.Count -gt 0 -and $outputObjects[-1].Type -eq 'Blank') { $outputObjects = $outputObjects | Select-Object -SkipLast 1 }
# Now process the output objects
if ($isPiped) {
# Output plain text for piping
foreach ($obj in $outputObjects) {
switch ($obj.Type) {
'Header' { "[$($obj.Name)] ($($obj.Status))" }
'Blank' { "" }
default { $obj.Text }
}
}
} else {
# Output colored text to the host
foreach ($obj in $outputObjects) {
switch ($obj.Type) {
'Header' {
$statColor = if ($obj.Status -eq 'Up') { 'Green' } else { 'Red' }
Write-Host "[$($obj.Name)] " -NoNewline -ForegroundColor Magenta
Write-Host "($($obj.Status))" -ForegroundColor $statColor
}
'Driver' { Write-Host $obj.Text -ForegroundColor DarkGray }
'MAC' { Write-Host $obj.Text -ForegroundColor Gray }
'Info' { Write-Host $obj.Text -ForegroundColor $obj.Color }
'Blank' { Write-Host "" }
}
}
}
}
Set-Alias ip Get-NetworkSummary -Scope Global
function global:Get-ContentHead {
param([string[]]$Path, [int]$n = 10)
if ($Path) { Get-Content $Path -TotalCount $n } else { $input | Select-Object -First $n }
}
Set-Alias head Get-ContentHead -Scope Global
function global:Get-ContentTail {
param([string[]]$Path, [int]$n = 10)
if ($Path) { Get-Content $Path -Tail $n } else { $input | Select-Object -Last $n }
}
Set-Alias tail Get-ContentTail -Scope Global
function global:Measure-Content {
param([string[]]$Path)
if ($Path) { Get-Content $Path | Measure-Object -Line -Word -Character } else { $input | Measure-Object -Line -Word -Character }
}
Set-Alias wc Measure-Content -Scope Global
# --- Developer Tools ---
# Install Git via winget
function global:Install-Git {
if (Get-Command git -ErrorAction SilentlyContinue) {
Write-Host "Git is already installed: $(git --version)" -ForegroundColor Green
return
}
Write-Host "Installing Git..." -ForegroundColor Yellow
winget install Git.Git -s winget --accept-source-agreements --accept-package-agreements
Update-EnvironmentPath
if (Get-Command git -ErrorAction SilentlyContinue) {
Write-Host "Git installed successfully: $(git --version)" -ForegroundColor Green
} else {
Write-Host "Git installation may require a terminal restart to take effect." -ForegroundColor Yellow
}
}
function global:gst { git status -sb }
function global:gco {
if ($args.Count -eq 0) {
$branch = git branch --format='%(refname:short)' | Out-GridView -Title "Select Branch to Checkout" -PassThru
if ($branch) { git checkout $branch }
} else {
git checkout $args
}
}
function global:gcmsg { git commit -m $args }
function global:gpush {
$branch = git symbolic-ref --short HEAD 2>$null
$upstream = git rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>$null
if ($branch -and -not $upstream) {
git push --set-upstream origin $branch
} else {
git push $args
}
}
function global:gpull { git pull $args }
function global:glog { git log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(auto)%d%C(reset)' --all }
function global:gaa { git add --all }
function global:gcb { git checkout -b $args }
function global:gcom {
if ($args) {
git add --all
git commit -m "$args"
} else {
Write-Host "--- Status ---" -ForegroundColor Cyan
git status -sb
git add --all
$msg = Read-Host "Commit Message"
if ($msg) { git commit -m $msg } else { Write-Warning "Commit cancelled." }
}
}
function global:gd { git diff $args }
function global:gbr { git branch $args }
function global:gsta { git stash push $args }
function global:gstp { git stash pop $args }
# --- Terminal Configuration ---
# Set Windows Terminal Appearance
function global:Set-WTAppearance {
param(
[string]$FontName = "JetBrainsMonoNL Nerd Font",
[double]$Opacity = 0.99,
[bool]$UseAcrylic = $false,
[bool]$UseAcrylicInTabRow = $true
)
$settingsPath = "$env:LOCALAPPDATA\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json"
if (-not (Test-Path $settingsPath)) { return }
try {
$jsonContent = Get-Content $settingsPath -Raw
# Remove JS-style comments (//) because standard JSON parsers (and older PS versions) fail on them
if ($PSVersionTable.PSVersion.Major -le 5) {
$jsonContent = $jsonContent -replace '(?m)^\s*//.*$',''
}
$json = $jsonContent | ConvertFrom-Json
if (-not $json.profiles.defaults) { $json.profiles | Add-Member -MemberType NoteProperty -Name "defaults" -Value ([PSCustomObject]@{}) }
if (-not $json.profiles.defaults.font) { $json.profiles.defaults | Add-Member -MemberType NoteProperty -Name "font" -Value ([PSCustomObject]@{}) }
# Check if update is needed
$needUpdate = $false
if ($json.profiles.defaults.font.face -ne $FontName) { $needUpdate = $true }
if ($UseAcrylic) {
if ($json.profiles.defaults.useAcrylic -ne $true) { $needUpdate = $true }
if ($json.profiles.defaults.acrylicOpacity -ne $Opacity) { $needUpdate = $true }
} else {
if ($json.profiles.defaults.PSObject.Properties['useAcrylic']) { $needUpdate = $true }
if ($json.profiles.defaults.PSObject.Properties['acrylicOpacity']) { $needUpdate = $true }
$intOpacity = if ($Opacity -le 1.0) { [int]($Opacity * 100) } else { $Opacity }
if ($json.profiles.defaults.opacity -ne $intOpacity) { $needUpdate = $true }
}
if ($json.useAcrylicInTabRow -ne $UseAcrylicInTabRow) { $needUpdate = $true }
if (-not $needUpdate) { return }
$json.profiles.defaults.font | Add-Member -MemberType NoteProperty -Name "face" -Value $FontName -Force
if ($UseAcrylic) {
$json.profiles.defaults | Add-Member -MemberType NoteProperty -Name "useAcrylic" -Value $true -Force
$json.profiles.defaults | Add-Member -MemberType NoteProperty -Name "acrylicOpacity" -Value $Opacity -Force
} else {
if ($json.profiles.defaults.PSObject.Properties['useAcrylic']) { $json.profiles.defaults.PSObject.Properties.Remove('useAcrylic') }
if ($json.profiles.defaults.PSObject.Properties['acrylicOpacity']) { $json.profiles.defaults.PSObject.Properties.Remove('acrylicOpacity') }
$intOpacity = if ($Opacity -le 1.0) { [int]($Opacity * 100) } else { $Opacity }
$json.profiles.defaults | Add-Member -MemberType NoteProperty -Name "opacity" -Value $intOpacity -Force
}
$json | Add-Member -MemberType NoteProperty -Name "useAcrylicInTabRow" -Value $UseAcrylicInTabRow -Force
$json | ConvertTo-Json -Depth 20 | Set-Content $settingsPath -Encoding UTF8
Write-Host "Windows Terminal appearance updated. Restart Terminal to see changes." -ForegroundColor Green
} catch {}
}
# Set VS Code Font
function global:Set-VSCodeFont {
param([string]$FontName = "JetBrainsMonoNL Nerd Font")
$settingsPath = "$env:APPDATA\Code\User\settings.json"
if (-not (Test-Path $settingsPath)) { return }
try {
$jsonContent = Get-Content $settingsPath -Raw
$jsonContent = $jsonContent -replace '(?m)^\s*//.*$',''
$json = $jsonContent | ConvertFrom-Json
if ($json.'terminal.integrated.fontFamily' -eq $FontName) { return }
$json | Add-Member -MemberType NoteProperty -Name "terminal.integrated.fontFamily" -Value $FontName -Force
$json | ConvertTo-Json -Depth 20 | Set-Content $settingsPath -Encoding UTF8
Write-Host "VS Code font updated to '$FontName'. Reload window to see changes." -ForegroundColor Green
} catch {}
}
# --- Profile Management ---
# Quick edit profile
function global:Edit-Profile {
param([string]$Editor = 'code')
if (Get-Command $Editor -ErrorAction SilentlyContinue) { & $Editor $PROFILE } else { notepad $PROFILE }
}
if (-not (Test-Path Alias:pro)) { Set-Alias pro Edit-Profile -Scope Global }
# Reload profile
function global:Import-Profile {
param([switch]$ClearCache)
# Clear cached files to force re-evaluation of settings (Oh My Posh init, WT settings check)
$filesToRemove = @(
"$env:TEMP\omp_init.ps1",
"$env:TEMP\wt_appearance.stamp",
"$env:TEMP\vscode_font.stamp"
)
$filesToRemove | ForEach-Object { if (Test-Path $_) { Remove-Item $_ -Force -ErrorAction SilentlyContinue } }
if ($ClearCache -and (Get-Command oh-my-posh -ErrorAction SilentlyContinue)) {
Write-Host "Cleaning Oh My Posh internal cache..." -ForegroundColor Yellow
oh-my-posh cache clean
}
@(
$Profile.AllUsersAllHosts,
$Profile.AllUsersCurrentHost,
$Profile.CurrentUserAllHosts,
$Profile.CurrentUserCurrentHost
) | ForEach-Object {
if (Test-Path $_) {
Write-Verbose "Running $_"
. $_
}
}
Write-Host "[$(Get-Date -Format 'HH:mm:ss')] Profiles reloaded and cache cleared." -ForegroundColor Green
}
if (-not (Test-Path Alias:reload)) { Set-Alias reload Import-Profile -Scope Global }
# Pull latest profile from GitHub
function global:Update-ProfileFromRemote {
$url = "https://raw.githubusercontent.com/brycefors/PowerShell-Profile/main/Microsoft.PowerShell_profile.ps1"
Write-Host "Downloading latest profile from GitHub..." -ForegroundColor Yellow
try {
$content = (Invoke-WebRequest $url -UseBasicParsing).Content -replace "`r`n", "`n" -replace "`n", "`r`n"
Set-Content -Path $PROFILE -Value $content -Encoding UTF8 -Force -NoNewline
Write-Host "Profile updated successfully." -ForegroundColor Green
Import-Profile
} catch {
Write-Error "Failed to update profile: $_"
}
}
Set-Alias pull-profile Update-ProfileFromRemote -Scope Global
# --- Completions ---
# Register winget autocomplete
# Invokes 'winget complete' to provide context-aware suggestions (packages, commands)
Register-ArgumentCompleter -Native -CommandName winget -ScriptBlock {
param($wordToComplete, $commandAst, $cursorPosition)
[Console]::InputEncoding = [Console]::OutputEncoding = $OutputEncoding = [System.Text.Utf8Encoding]::new()
$Local:word = $wordToComplete.Replace('"', '""')
$Local:ast = $commandAst.ToString().Replace('"', '""')
winget complete --word="$Local:word" --commandline "$Local:ast" --position $cursorPosition | ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
}
}
# --- Startup Execution ---
# Auto-configure font if running in Windows Terminal
# Stamp files prevent reading/writing JSON settings on every startup
# We only run the heavy JSON logic if the stamp is missing or the settings file is newer than the stamp.
if ($env:WT_SESSION) {
$wtStamp = "$env:TEMP\wt_appearance.stamp"
$wtSettings = "$env:LOCALAPPDATA\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json"
if (-not (Test-Path $wtStamp) -or
((Test-Path $wtSettings) -and [System.IO.File]::GetLastWriteTime($wtSettings) -gt [System.IO.File]::GetLastWriteTime($wtStamp))) {
Set-WTAppearance
[System.IO.File]::WriteAllText($wtStamp, (Get-Date).ToString())
}
}
if ($env:TERM_PROGRAM -eq 'vscode') {
$vsStamp = "$env:TEMP\vscode_font.stamp"
$vsSettings = "$env:APPDATA\Code\User\settings.json"
if (-not (Test-Path $vsStamp) -or
((Test-Path $vsSettings) -and [System.IO.File]::GetLastWriteTime($vsSettings) -gt [System.IO.File]::GetLastWriteTime($vsStamp))) {
Set-VSCodeFont
[System.IO.File]::WriteAllText($vsStamp, (Get-Date).ToString())
}
}
# Check for scheduled reboot
$pendingReboot = Get-PendingReboot
if ($pendingReboot) {
Write-Host "WARNING: System is scheduled to reboot at $($pendingReboot.ToString())" -ForegroundColor Red -BackgroundColor Black
Write-Host "Run 'areboot' to cancel." -ForegroundColor Yellow
}