-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMicrosoft.PowerShell_profile.ps1
More file actions
2468 lines (2081 loc) · 83.8 KB
/
Microsoft.PowerShell_profile.ps1
File metadata and controls
2468 lines (2081 loc) · 83.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ----------------------------------
# 1) Path for the Settings File
# ----------------------------------
$ProfileFolder = Split-Path -Parent $PROFILE
$SettingsFileName = "powershell.config.json"
$Global:SettingsFile = Join-Path $ProfileFolder $SettingsFileName
# ----------------------------------
# 2) Default Values
# ----------------------------------
$Global:DefaultSettings = [ordered]@{
"Microsoft.PowerShell.Profile:PromptColorScheme" = "Default" # Default prompt color scheme
"Microsoft.PowerShell.Profile:DefaultPrompt" = $false # If true, use PowerShell's default prompt instead of the custom one
"Microsoft.PowerShell.Profile:AskCreateCodeFolder" = $true # Whether to ask for the creation of the "Code" folder if missing
"Microsoft.PowerShell.Profile:CodeFolderName" = "Code" # Default name for the code folder
"Microsoft.PowerShell.Profile:EnableRandomTitle" = $false # Enables "Hackerman" style random PowerShell title
}
# ----------------------------------
# 3) Function to Load User Settings
# ----------------------------------
function Get-UserSettings {
param(
[string]$Path = $Global:SettingsFile
)
# If the file does not exist, create it using default values
if (-not (Test-Path $Path)) {
Write-Host "File '$Path' does not exist. Creating default settings file..."
$DefaultJson = ($Global:DefaultSettings | ConvertTo-Json -Depth 10)
$DefaultJson | Out-File -FilePath $Path -Encoding UTF8
return $Global:DefaultSettings
}
else {
# Try to read and parse JSON
try {
$jsonContent = Get-Content -Path $Path -Raw
$parsed = $null
if ($jsonContent) {
$parsed = $jsonContent | ConvertFrom-Json
}
if (-not $parsed) {
Write-Warning "The file '$Path' is empty or not valid JSON. Default values will be used."
return $Global:DefaultSettings
}
# Convert the $parsed object to a hashtable and merge with DefaultSettings
$userSettings = @{}
foreach ($key in $parsed.psobject.Properties.Name) {
$userSettings[$key] = $parsed."$key"
}
# For each default key, if not present in userSettings, assign the default one
foreach ($defaultKey in $Global:DefaultSettings.Keys) {
if (-not $userSettings.ContainsKey($defaultKey)) {
$userSettings[$defaultKey] = $Global:DefaultSettings[$defaultKey]
}
}
$Global:UserSettings = $userSettings
return $userSettings
}
catch {
Write-Warning "Could not read or parse '$Path': $_"
Write-Warning "Default values will be used."
return $Global:DefaultSettings
}
}
}
# ----------------------------------
# 4) Load settings into a global variable
# ----------------------------------
$Global:UserSettings = Get-UserSettings $Global:SettingsFile
# ----------------------------------
# 5) Functions to Save User Settings (optional)
# Use them if you want to modify values and
# persist them into the JSON file.
# ----------------------------------
function Save-UserSettings {
param(
[hashtable]$NewSettings = $Global:Usersettings
)
$json = $NewSettings | ConvertTo-Json -Depth 10
$json | Out-File -FilePath $Global:SettingsFile -Encoding UTF8
}
Enum OS {
Windows
Linux
MacOS
}
$Kernel = if ($IsWindows) {
[OS]::Windows
}
elseif ($IsLinux) {
[OS]::Linux
}
elseif ($IsMacOS) {
[OS]::MacOS
}
if ($IsWindows) {
$env:USER = $env:USERNAME
}
[String]$SPWD
$DirArray = @()
# ------------------------------------------------------
# Handle 'Code' folder based on loaded User Settings
# ------------------------------------------------------
$CODE = Join-Path -Path $HOME -ChildPath $Global:UserSettings["Microsoft.PowerShell.Profile:CodeFolderName"]
$AskCreateCodeFolder = $Global:UserSettings["Microsoft.PowerShell.Profile:AskCreateCodeFolder"]
if (!(Test-Path -Path $CODE) -and $AskCreateCodeFolder) {
$CreateCodeFolder = Read-Host "`'$CODE`' folder not exists, create it? (Y/N)"
if ($CreateCodeFolder -eq "Y") {
New-Item -Path $CODE -ItemType Directory | Out-Null
}
}
# ----------------------------------
# PromptColorSchemes enum
# ----------------------------------
enum PromptColorSchemes {
Default
Blue
Green
Cyan
Red
Magenta
Yellow
Gray
Random
Asturias
Spain
Hackerman
}
# ----------------------------------
# Function to set the color scheme
# ----------------------------------
function Set-PromptColorScheme {
[CmdletBinding()]
param (
[PromptColorSchemes]$ColorScheme
)
if ($ColorScheme -eq [PromptColorSchemes]::Hackerman) {
if ($Global:UserSettings["Microsoft.PowerShell.Profile:EnableRandomTitle"]) {
Set-RandomPowerShellTitle
}
}
# Color palette
$Colors = @{
"Blue" = @([ConsoleColor]::Blue, [ConsoleColor]::DarkBlue)
"Green" = @([ConsoleColor]::Green, [ConsoleColor]::DarkGreen)
"Cyan" = @([ConsoleColor]::Cyan, [ConsoleColor]::DarkCyan)
"Red" = @([ConsoleColor]::Red, [ConsoleColor]::DarkRed)
"Magenta" = @([ConsoleColor]::Magenta, [ConsoleColor]::DarkMagenta)
"Yellow" = @([ConsoleColor]::Yellow, [ConsoleColor]::DarkYellow)
"White" = @([ConsoleColor]::White, [ConsoleColor]::DarkGray)
"Gray" = @([ConsoleColor]::Gray, [ConsoleColor]::DarkGray)
}
$ColorSchemes = @{
[PromptColorSchemes]::Default = $Colors["White"]
[PromptColorSchemes]::Blue = $Colors["Blue"]
[PromptColorSchemes]::Green = $Colors["Green"]
[PromptColorSchemes]::Cyan = $Colors["Cyan"]
[PromptColorSchemes]::Red = $Colors["Red"]
[PromptColorSchemes]::Magenta = $Colors["Magenta"]
[PromptColorSchemes]::Yellow = $Colors["Yellow"]
[PromptColorSchemes]::Gray = $Colors["Gray"]
[PromptColorSchemes]::Random = @(
$Colors[$($Colors.Keys | Get-Random)][0],
$Colors[$($Colors.Keys | Get-Random)][1]
)
[PromptColorSchemes]::Asturias = @($Colors["Blue"][0], $Colors["Yellow"][1])
[PromptColorSchemes]::Spain = @($Colors["Red"][0], $Colors["Yellow"][1])
[PromptColorSchemes]::Hackerman = @($Colors["Green"][0], $Colors["Gray"][1])
}
$Global:PromptColors = $ColorSchemes[$ColorScheme]
$Global:UserSettings["Microsoft.PowerShell.Profile:PromptColorScheme"] = $ColorScheme.toString()
}
# ----------------------------------
# Variations for 'Hackerman' title
# ----------------------------------
$RandomP = @("p", "P", "ρ", "¶", "₱", "ℙ", "℗", "𝒫", "𝓟", "𝔓", "𝕻", "𝖯", "𝗣", "𝘗", "𝙋", "𝚙", "𝚙", "𝖕", "𝗽", "𝘱")
$RandomO = @("o", "O", "0", "ø", "ɵ", "º", "θ", "ω", "ჿ", "ᴏ", "ᴑ", "⊝", "Ο", "ο", "𝐨", "𝐎", "𝑂", "𝑜", "𝒐", "𝒪")
$RandomW = @("w", "W", "ω", "ѡ", "ẁ", "ẃ", "ẅ", "ẇ", "ѡ", "ѿ", "ᴡ", "𝐰", "𝑤", "𝑾", "𝒲", "𝓌", "𝔀", "𝔚", "𝔴", "𝕎")
$RandomE = @("e", "E", "3", "€", "є", "ё", "ē", "ė", "ę", "ε", "ξ", "ℯ", "𝐞", "𝐄", "𝑒", "𝐸", "𝑬", "𝓮", "𝔢", "𝔼")
$RandomR = @("r", "R", "®", "ř", "я", "г", "ɾ", "ṛ", "ɼ", "ṟ", "ṙ", "ṝ", "ℛ", "ℜ", "ℝ", "𝐫", "𝑅", "𝓻", "𝔯", "𝕣")
$RandomS = @("s", "S", "5", "$", "§", "∫", "š", "ś", "ş", "ς", "ș", "ƨ", "𝐬", "𝑆", "𝒔", "𝓈", "𝓢", "𝔰", "𝔖", "𝕊")
$RandomH = @("h", "H", "#", "η", "ħ", "һ", "ḥ", "ḧ", "ḩ", "ḣ", "ℎ", "ℋ", "ℌ", "𝒽", "𝐡", "𝐇", "𝐻", "𝒉", "𝓗", "𝕳")
$RandomL = @("l", "L", "1", "!", "|", "ł", "£", "ℓ", "ľ", "ĺ", "ℒ", "Ⅼ", "Ι", "𝐥", "𝐋", "𝑙", "𝐿", "𝑳", "𝓵", "𝓛")
function Set-RandomPowerShellTitle {
$title = ""
$title += $RandomP | Get-Random
$title += $RandomO | Get-Random
$title += $RandomW | Get-Random
$title += $RandomE | Get-Random
$title += $RandomR | Get-Random
$title += $RandomS | Get-Random
$title += $RandomH | Get-Random
$title += $RandomE | Get-Random
$title += $RandomL | Get-Random
$title += $RandomL | Get-Random
$Host.UI.RawUI.WindowTitle = $title
}
[ConsoleColor[]]$PromptColors = @()
# Read if we want the default prompt
$DefaultPrompt = $Global:UserSettings["Microsoft.PowerShell.Profile:DefaultPrompt"]
# ----------------------------------
# Custom Prompt
# ----------------------------------
function Prompt() {
# Always set a window title
$Host.UI.RawUI.WindowTitle = "PowerShell"
if ($DefaultPrompt) {
Write-Host "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1))" -NoNewline
return " "
}
# Set the color scheme
Set-PromptColorScheme -ColorScheme $Global:UserSettings["Microsoft.PowerShell.Profile:PromptColorScheme"]
Write-Host "||" -NoNewline -ForegroundColor $PromptColors[1]
Write-Host $env:USER -NoNewline -ForegroundColor $PromptColors[0]
Write-Host "@" -NoNewline -ForegroundColor $PromptColors[1]
Write-Host $Kernel -NoNewline -ForegroundColor $PromptColors[0]
Write-Host "|-|" -NoNewline -ForegroundColor $PromptColors[1]
$SPWD = if ($PWD.Path.StartsWith($HOME)) {
"~$([IO.Path]::DirectorySeparatorChar)$($PWD.Path.Substring($HOME.Length))"
}
else {
$PWD.Path
}
$DirArray = $SPWD.Split([IO.Path]::DirectorySeparatorChar)
$IsFirstFolder = $true
foreach ($FolderName in $DirArray) {
if ($FolderName.Length -eq 0) {
continue
}
if (!$IsFirstFolder -or ($FolderName -ne "~" -and !$IsWindows)) {
Write-Host $([IO.Path]::DirectorySeparatorChar) -NoNewline -ForegroundColor $PromptColors[1]
}
Write-Host $FolderName -NoNewline -ForegroundColor $PromptColors[0]
$IsFirstFolder = $false
}
Write-Host "||`n" -NoNewline -ForegroundColor $PromptColors[1]
Write-Host $("|>" * ($NestedPromptLevel + 1)) -NoNewline -ForegroundColor $PromptColors[1]
return " "
}
# ---------------------------------------------------------------------------
# OTHER FUNCTIONS (mostly unchanged, just relocated in the profile)
# ---------------------------------------------------------------------------
function Set-PWDClipboard {
Set-Clipboard $PWD
}
function Get-PublicIP {
$PublicIP = Invoke-RestMethod -Uri "https://api.ipify.org"
return $PublicIP
}
function Get-DiskSpace {
$drives = Get-PSDrive -PSProvider FileSystem | ForEach-Object {
[PSCustomObject]@{
Drive = $_.Name
UsedGB = [math]::round(($_.Used / 1GB), 2)
FreeGB = [math]::round(($_.Free / 1GB), 2)
TotalGB = [math]::round(($_.Used + $_.Free) / 1GB, 2)
}
}
$drives | Format-Table -AutoSize
}
function Get-Weather {
param (
[string]$Place,
[String]$Language
)
if (-not $Place) {
# Get current city from IP
$Place = (Invoke-RestMethod -Uri "https://ipinfo.io").city
while (-not $Place) {
$Place = (Invoke-RestMethod -Uri "https://ipinfo.io").city
Start-Sleep -Seconds 1
}
}
if (-not $Language) {
$Language = (Get-Culture).Name.Substring(0, 2)
}
$Response = ""
try {
$RequestUri = "https://wttr.in/~$Place?lang=$Language"
$Response = Invoke-RestMethod -Uri $RequestUri -ErrorAction SilentlyContinue
}
catch {
return "Error: The place '$Place' is not found"
}
return $Response
}
function Get-ChtShHelp {
param (
[Parameter(Mandatory = $true)]
[string]$Command
)
try {
$response = Invoke-WebRequest -Uri "https://cht.sh/$Command" -UseBasicParsing
return $response.Content
}
catch {
Write-Error "Failed to retrieve help for the command '$Command'. Check your connection or the command entered."
}
}
function Get-PowershellChtShHelp {
param (
[Parameter(Mandatory = $true)]
[string]$Command
)
Get-ChtShHelp -Command "powershell/$Command"
}
function Stop-ProcessConstantly {
param (
[Parameter(Mandatory)]
[string]$ProcessName
)
$i = 0
while ($true) {
try {
Stop-Process -Name $ProcessName -ErrorAction Stop
$i++
Write-Host "[$i] - Process '$ProcessName' stopped successfully." -ForegroundColor Green
}
catch {
continue
}
}
}
<#
.SYNOPSIS
Displays a directory tree structure in the console.
.DESCRIPTION
The `Show-DirectoryTree` function recursively lists the contents of a directory in a tree-like format.
It supports displaying both folders and files, with options to customize recursion depth and respect `.gitignore` rules.
.PARAMETER Path
Specifies the path of the directory to list. Defaults to the current directory (`.`).
.PARAMETER Depth
Specifies the maximum depth of recursion. Defaults to unlimited depth (`[int]::MaxValue`).
.PARAMETER IncludeFiles
Includes files in the output in addition to folders. This is an optional switch parameter.
.PARAMETER RespectGitIgnore
Respects `.gitignore` rules when listing files and directories. This is an optional switch parameter.
.PARAMETER AdditionalIgnore
An array of additional ignore patterns to apply.
.EXAMPLE
Show-DirectoryTree
Displays the directory tree of the current directory.
.EXAMPLE
Show-DirectoryTree -Path "C:\Projects" -Depth 2
Displays the directory tree of "C:\Projects" up to a depth of 2 levels.
.EXAMPLE
Show-DirectoryTree -Path "C:\Projects" -IncludeFiles
Displays the directory tree of "C:\Projects", including files.
.EXAMPLE
Show-DirectoryTree -Path "C:\Projects" -IncludeFiles -RespectGitIgnore
Displays the directory tree of "C:\Projects", including files, while respecting `.gitignore` rules.
.NOTES
This function uses recursion to traverse directories and outputs a tree-like structure with proper indentation.
#>
function Show-DirectoryTree {
[CmdletBinding()]
param(
[Parameter(Position = 0, HelpMessage = 'Path of the directory to list')]
[string] $Path = '.',
[Parameter(HelpMessage = 'Maximum recursion depth (omit = unlimited)')]
[int] $Depth = [int]::MaxValue,
[Parameter(HelpMessage = 'Include files in addition to folders')]
[switch] $IncludeFiles,
[Parameter(HelpMessage = 'When listing files, omit those matching .gitignore or AdditionalIgnore')]
[switch] $RespectGitIgnore,
[Parameter(HelpMessage = 'Array of extra ignore patterns (in .gitignore syntax)')]
[string[]] $AdditionalIgnore = @()
)
# Validate path exists before proceeding
if (-not (Test-Path -Path $Path)) {
Write-Error "Path '$Path' does not exist"
return
}
# Get full path safely
$rootFull = (Resolve-Path -Path $Path).ProviderPath
# Write the name of the root directory
$rootName = Split-Path -Path $rootFull -Leaf
Write-Output $rootName
# Prepare Convert-GitignoreLine helper
function Convert-GitignoreLine {
param([string] $line, [string] $baseDir)
$t = $line.Trim()
if ($t -match '^(#|\s*$)') { return }
$neg = $t.StartsWith('!'); if ($neg) { $t = $t.Substring(1).Trim() }
$anch = $t.StartsWith('/'); if ($anch) { $t = $t.Substring(1) }
$dirOnly = $t.EndsWith('/'); if ($dirOnly) { $t = $t.TrimEnd('/') }
[PSCustomObject]@{
Pattern = $t
Negated = $neg
Anchored = $anch
DirOnly = $dirOnly
BaseDir = $baseDir
}
}
# Build patterns array if needed
if ($IncludeFiles.IsPresent -and $RespectGitIgnore.IsPresent) {
$patterns = @()
# 1) AdditionalIgnore entries (base is root)
foreach ($pat in $AdditionalIgnore) {
if ($p = Convert-GitignoreLine $pat $rootFull) {
$patterns += $p
}
}
# 2) All .gitignore under tree
Get-ChildItem -Path $rootFull -Filter '.gitignore' -File -Recurse -Force |
ForEach-Object {
$dir = Split-Path $_.FullName -Parent
Get-Content -LiteralPath $_.FullName | ForEach-Object {
if ($p = Convert-GitignoreLine $_ $dir) {
$patterns += $p
}
}
}
# testIgnore uses combined patterns
$testIgnore = {
param($fullPath, $isDir)
foreach ($r in $patterns) {
if ($fullPath -notlike "$($r.BaseDir)*") { continue }
$rel = $fullPath.Substring($r.BaseDir.Length).TrimStart('\', '/').Replace('\', '/')
if ($r.DirOnly -and -not $isDir) { continue }
$match = $false
if ($r.Anchored) {
if ($rel -like $r.Pattern -or $rel -like "$($r.Pattern)/*") { $match = $true }
}
elseif ($r.Pattern.Contains('/')) {
if ($rel -like "*$($r.Pattern)*") { $match = $true }
}
else {
$leaf = if ($rel) { Split-Path $rel -Leaf } else { '' }
if ($leaf -like $r.Pattern) { $match = $true }
}
if ($match) { return (-not $r.Negated) }
}
return $false
}
}
else {
# never ignore
$testIgnore = { return $false }
}
# Recursive walker
function Walk {
param(
[string] $dir,
[string] $prefix,
[int] $level
)
if ($level -ge $Depth) { return }
$items = Get-ChildItem -LiteralPath $dir -Force |
Where-Object { -not ($_.Name.StartsWith('.') -or ($_.Attributes -band [IO.FileAttributes]::Hidden)) }
$dirs = $items |
Where-Object { $_.PSIsContainer -and -not (& $testIgnore $_.FullName $true) } |
Sort-Object Name
$files = if ($IncludeFiles) {
$items |
Where-Object { -not $_.PSIsContainer -and -not (& $testIgnore $_.FullName $false) } |
Sort-Object Name
}
else { @() }
# Force arrays
$dirs = @($dirs)
$files = @($files)
$entries = $dirs + $files
for ($i = 0; $i -lt $entries.Count; $i++) {
$item = $entries[$i]
$isLast = ($i -eq $entries.Count - 1)
$branch = if ($isLast) { '└── ' } else { '├── ' }
Write-Output ($prefix + $branch + $item.Name)
if ($item.PSIsContainer) {
$newPrefix = if ($isLast) { "$prefix " } else { "$prefix│ " }
Walk -dir $item.FullName -prefix $newPrefix -level ($level + 1)
}
}
}
# Start walking
Walk -dir $rootFull -prefix '' -level 0
}
<#
.SYNOPSIS
Recursively retrieves the content of files in a directory while respecting .gitignore rules and additional ignore patterns.
.DESCRIPTION
The `Get-ContentRecursiveIgnore` function enumerates files in a specified directory and its subdirectories, ignoring files and directories based on .gitignore rules and additional ignore patterns provided by the user. It outputs the content of the files, optionally formatted with Markdown fenced code blocks.
.PARAMETER Path
Specifies the root directory to start the recursive enumeration. Defaults to the current directory (".").
.PARAMETER AdditionalIgnore
An array of additional ignore patterns to apply, in addition to the patterns specified in .gitignore files.
.PARAMETER UseMarkdownFence
A boolean flag indicating whether to format the output with Markdown fenced code blocks. Defaults to `$true`.
.EXAMPLE
Get-ContentRecursiveIgnore -Path "C:\Projects" -AdditionalIgnore @("*.log", "!important.log") -UseMarkdownFence $false
Retrieves the content of all files in the "C:\Projects" directory and its subdirectories, ignoring files matching the patterns in .gitignore and the additional patterns "*.log" (except "important.log"). Outputs the content without Markdown formatting.
.EXAMPLE
Get-ContentRecursiveIgnore -Path "C:\Projects" -UseMarkdownFence $true
Retrieves the content of all files in the "C:\Projects" directory and its subdirectories, ignoring files matching the patterns in .gitignore. Outputs the content formatted with Markdown fenced code blocks.
.NOTES
- The function respects .gitignore rules found in the directory tree.
- Additional ignore patterns can be specified using the `AdditionalIgnore` parameter.
- The function supports syntax highlighting for various file types when `UseMarkdownFence` is enabled, based on file extensions.
#>
function Get-ContentRecursiveIgnore {
[CmdletBinding()]
param(
[string] $Path = ".",
[string[]] $AdditionalIgnore = @(),
[bool] $UseMarkdownFence = $true
)
# Validate path exists before proceeding
if (-not (Test-Path -Path $Path)) {
Write-Error "Path '$Path' does not exist"
return
}
# Show the directory tree before processing file contents
Show-DirectoryTree -Path $Path -IncludeFiles -RespectGitIgnore -AdditionalIgnore $AdditionalIgnore
Write-Output "`n`n"
# Get full path safely
$baseFull = (Resolve-Path -Path $Path).ProviderPath
# Build a case-insensitive extension → Markdown language map
$extensionMap = [hashtable]::new([System.StringComparer]::OrdinalIgnoreCase)
$literalMap = @{
ps1 = 'powershell'; py = 'python'; js = 'javascript'; ts = 'typescript'; html = 'html'; css = 'css';
json = 'json'; md = 'markdown'; sh = 'bash'; c = 'c'; cpp = 'cpp'; cs = 'csharp'; java = 'java';
go = 'go'; php = 'php'; rb = 'ruby'; rs = 'rust'; kt = 'kotlin'; swift = 'swift'; sql = 'sql'
}
foreach ($entry in $literalMap.GetEnumerator()) {
$extensionMap[$entry.Key] = $entry.Value
}
# Parse a .gitignore line into a pattern object
function Convert-GitignoreLine {
param([string] $line, [string] $baseDir)
$text = $line.Trim()
if ($text -match '^(#|\s*$)') { return }
$negated = $text.StartsWith('!')
if ($negated) { $text = $text.Substring(1).Trim() }
$anchored = $text.StartsWith('/')
if ($anchored) { $text = $text.Substring(1) }
$dirOnly = $text.EndsWith('/')
if ($dirOnly) { $text = $text.TrimEnd('/') }
return [PSCustomObject]@{
Pattern = $text
Negated = $negated
Anchored = $anchored
DirOnly = $dirOnly
BaseDir = $baseDir
}
}
# Load ignore patterns from .gitignore files
$baseFull = (Resolve-Path $Path).ProviderPath
$patterns = @()
foreach ($ignore in $AdditionalIgnore) {
if ($p = Convert-GitignoreLine $ignore $baseFull) { $patterns += $p }
}
Get-ChildItem -Path $baseFull -Filter '.gitignore' -File -Recurse -Force | ForEach-Object {
$dir = Split-Path $_.FullName -Parent
Get-Content $_.FullName | ForEach-Object {
if ($p = Convert-GitignoreLine $_ $dir) { $patterns += $p }
}
}
# Scriptblock to test whether a path should be ignored
$testIgnore = {
param([string] $fullPath, [bool] $isDirectory)
foreach ($rule in $patterns) {
if ($fullPath -notlike "$($rule.BaseDir)*") { continue }
$relative = $fullPath.Substring($rule.BaseDir.Length).TrimStart('\', '/').Replace('\', '/')
if ($rule.DirOnly -and -not $isDirectory) { continue }
$matched = $false
if ($rule.Anchored) {
if ($relative -like "$($rule.Pattern)" -or $relative -like "$($rule.Pattern)/*") { $matched = $true }
}
elseif ($rule.Pattern.Contains('/')) {
if ($relative -like "*$($rule.Pattern)*") { $matched = $true }
}
else {
$leaf = if ($relative) { Split-Path $relative -Leaf } else { "" }
if ($leaf -like $rule.Pattern) { $matched = $true }
}
if ($matched) { return -not $rule.Negated }
}
return $false
}
# Recursively enumerate files that are not ignored
function Enumerate {
param([string] $directory)
Get-ChildItem -Path $directory -Force | ForEach-Object {
if ($_.Name.StartsWith('.') -or ($_.Attributes -band [IO.FileAttributes]::Hidden)) { return }
if (& $testIgnore $_.FullName $_.PSIsContainer) { return }
if ($_.PSIsContainer) {
Enumerate $_.FullName
}
else {
[PSCustomObject]@{
FullPath = $_.FullName
RelPath = $_.FullName.Substring($baseFull.Length).TrimStart('\', '/').Replace('\', '/')
}
}
}
}
# Generate output with fenced code blocks
$files = Enumerate $baseFull
$output = $files | Sort-Object FullPath | ForEach-Object {
$relPath = $_.RelPath
$ext = [IO.Path]::GetExtension($_.FullPath).TrimStart('.')
$lang = if ($extensionMap.ContainsKey($ext)) { $extensionMap[$ext] } else { '' }
$openFence = '```' + $lang
$closeFence = '```'
$content = Get-Content -Raw -LiteralPath $_.FullPath
if ($UseMarkdownFence) {
"$relPath`n$openFence`n$content`n$closeFence"
}
else {
"$relPath`n$content"
}
}
return ($output -join "`n`n")
}
# ---------------------------------------------------------------------------
# PIP WRAPPER FUNCTIONS
# ---------------------------------------------------------------------------
# Find original pip executables by their full path to avoid alias conflicts
$Global:OriginalPipPath = $null
$Global:OriginalPip3Path = $null
# Search for pip in PATH directories
$pathDirs = $env:PATH -split ';'
foreach ($dir in $pathDirs) {
if (Test-Path $dir) {
$pipExe = Get-ChildItem -Path $dir -Name "pip.exe" -ErrorAction SilentlyContinue | Select-Object -First 1
if ($pipExe -and -not $Global:OriginalPipPath) {
$Global:OriginalPipPath = Join-Path $dir $pipExe
}
$pip3Exe = Get-ChildItem -Path $dir -Name "pip3.exe" -ErrorAction SilentlyContinue | Select-Object -First 1
if ($pip3Exe -and -not $Global:OriginalPip3Path) {
$Global:OriginalPip3Path = Join-Path $dir $pip3Exe
}
}
}
# If .exe not found, try without extension (Linux/macOS style)
if (-not $Global:OriginalPipPath) {
foreach ($dir in $pathDirs) {
if (Test-Path $dir) {
$pipExe = Get-ChildItem -Path $dir -Name "pip" -ErrorAction SilentlyContinue | Select-Object -First 1
if ($pipExe) {
$Global:OriginalPipPath = Join-Path $dir $pipExe
break
}
}
}
}
if (-not $Global:OriginalPip3Path) {
foreach ($dir in $pathDirs) {
if (Test-Path $dir) {
$pip3Exe = Get-ChildItem -Path $dir -Name "pip3" -ErrorAction SilentlyContinue | Select-Object -First 1
if ($pip3Exe) {
$Global:OriginalPip3Path = Join-Path $dir $pip3Exe
break
}
}
}
}
function Invoke-PipWrapper {
if (-not $Global:OriginalPipPath -or -not (Test-Path $Global:OriginalPipPath)) {
Write-Error "pip: command not found"
return
}
# If this is an install command and we're not in a virtual environment, show warning
if ($args -and $args[0] -eq "install" -and -not $env:VIRTUAL_ENV -and -not $env:CONDA_DEFAULT_ENV) {
$hasGlobalFlag = $args -contains "--global"
if (-not $hasGlobalFlag) {
Write-Host ""
Write-Host "⚠️ WARNING: Installing packages globally (not in virtual environment)." -ForegroundColor Yellow
Write-Host "Recommended: " -ForegroundColor Gray -NoNewline
Write-Host "python -m venv venv" -ForegroundColor Green -NoNewline
Write-Host " then activate it." -ForegroundColor Gray
Write-Host "Or use: " -ForegroundColor Gray -NoNewline
Write-Host "pip install $($args[1]) --global" -ForegroundColor Yellow
Write-Host ""
Write-Host "Press Enter to continue or Ctrl+C to cancel."
$null = Read-Host
}
# Remove custom --global flag
$cleanArgs = $args | Where-Object { $_ -ne "--global" }
& $Global:OriginalPipPath @cleanArgs
} else {
# For all other commands, just pass through directly
& $Global:OriginalPipPath @args
}
}
function Invoke-Pip3Wrapper {
if (-not $Global:OriginalPip3Path -or -not (Test-Path $Global:OriginalPip3Path)) {
Write-Error "pip3: command not found"
return
}
# If this is an install command and we're not in a virtual environment, show warning
if ($args -and $args[0] -eq "install" -and -not $env:VIRTUAL_ENV -and -not $env:CONDA_DEFAULT_ENV) {
$hasGlobalFlag = $args -contains "--global"
if (-not $hasGlobalFlag) {
Write-Host ""
Write-Host "⚠️ WARNING: Installing packages globally (not in virtual environment)." -ForegroundColor Yellow
Write-Host "Recommended: " -ForegroundColor Gray -NoNewline
Write-Host "python -m venv venv" -ForegroundColor Green -NoNewline
Write-Host " then activate it." -ForegroundColor Gray
Write-Host "Or use: " -ForegroundColor Gray -NoNewline
Write-Host "pip3 install $($args[1]) --global" -ForegroundColor Yellow
Write-Host ""
Write-Host "Press Enter to continue or Ctrl+C to cancel."
$null = Read-Host
}
# Remove custom --global flag
$cleanArgs = $args | Where-Object { $_ -ne "--global" }
& $Global:OriginalPip3Path @cleanArgs
} else {
# For all other commands, just pass through directly
& $Global:OriginalPip3Path @args
}
}
# Aliases
Set-Alias -Name vim -Value nvim
Set-Alias -Name vi -Value vim
Set-Alias -Name gvim -Value vim
Set-Alias -Name wrh -Value Write-Host
Set-Alias -Name cpwd -Value Set-PWDClipboard
Set-Alias -Name tree -Value Show-DirectoryTree
Set-Alias -Name gemini -Value Invoke-GeminiChat
Set-Alias -Name sgcm -Value Invoke-SuggestCommitMessage
# Create aliases only if the original commands exist
if ($Global:OriginalPipPath -and (Test-Path $Global:OriginalPipPath)) {
Set-Alias -Name pip -Value Invoke-PipWrapper -Force
}
if ($Global:OriginalPip3Path -and (Test-Path $Global:OriginalPip3Path)) {
Set-Alias -Name pip3 -Value Invoke-Pip3Wrapper -Force
}
# ---------------------------------------------------------------------------
# MATHEMATICAL CONSTANTS AND FUNCTIONS
# ---------------------------------------------------------------------------
# Constants
$Global:PI = [Math]::PI
$Global:E = [Math]::E
# Functions
function Get-Sin {
param([double]$Angle)
return [Math]::Sin($Angle)
}
function Get-Cos {
param([double]$Angle)
return [Math]::Cos($Angle)
}
function Get-Tan {
param([double]$Angle)
return [Math]::Tan($Angle)
}
function Get-Asin {
param([double]$Value)
return [Math]::Asin($Value)
}
function Get-Acos {
param([double]$Value)
return [Math]::Acos($Value)
}
function Get-Atan {
param([double]$Value)
return [Math]::Atan($Value)
}
function Get-Atan2 {
param([double]$y, [double]$x)
return [Math]::Atan2($y, $x)
}
function Get-Sqrt {
param([double]$Number)
return [Math]::Sqrt($Number)
}
function Get-Pow {
param([double]$Base, [double]$Exponent)
return [Math]::Pow($Base, $Exponent)
}
function Get-Log {
param([double]$Number)
return [Math]::Log($Number)
}
function Get-Log10 {
param([double]$Number)
return [Math]::Log10($Number)
}
function Get-Exp {
param([double]$Power)
return [Math]::Exp($Power)
}
function Get-Abs {
param([double]$Value)
return [Math]::Abs($Value)
}
function Get-Round {
param([double]$Value, [int]$Digits = 0)
return [Math]::Round($Value, $Digits)
}
function Get-Ceiling {
param([double]$Value)
return [Math]::Ceiling($Value)
}
function Get-Floor {
param([double]$Value)
return [Math]::Floor($Value)
}
function Get-Max {
param([double]$Val1, [double]$Val2)
return [Math]::Max($Val1, $Val2)
}
function Get-Min {
param([double]$Val1, [double]$Val2)
return [Math]::Min($Val1, $Val2)
}
function Get-Truncate {
param([double]$Value)
return [Math]::Truncate($Value)
}
function Get-Sign {
param([double]$Value)
return [Math]::Sign($Value)
}
# Copilot aliases
function ghcs {
param(
[ValidateSet('gh', 'git', 'shell')]
[Alias('t')]
[String]$Target = 'shell',
[Parameter(Position = 0, ValueFromRemainingArguments)]
[string]$Prompt
)
begin {
$executeCommandFile = New-TemporaryFile
$envGhDebug = $Env:GH_DEBUG
}
process {
if ($PSBoundParameters['Debug']) {
$Env:GH_DEBUG = 'api'
}
gh copilot suggest -t $Target -s "$executeCommandFile" $Prompt
}
end {
if ($executeCommandFile.Length -gt 0) {
$executeCommand = (Get-Content -Path $executeCommandFile -Raw).Trim()
[Microsoft.PowerShell.PSConsoleReadLine]::AddToHistory($executeCommand)
$now = Get-Date
$executeCommandHistoryItem = [PSCustomObject]@{
CommandLine = $executeCommand
ExecutionStatus = [Management.Automation.Runspaces.PipelineState]::NotStarted
StartExecutionTime = $now
EndExecutionTime = $now.AddSeconds(1)
}
Add-History -InputObject $executeCommandHistoryItem
Write-Host "`n"
Invoke-Expression $executeCommand