-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearch-FileContent.ps1
More file actions
1245 lines (1061 loc) · 44.1 KB
/
Copy pathSearch-FileContent.ps1
File metadata and controls
1245 lines (1061 loc) · 44.1 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
function Search-FileContent
{
<#
.SYNOPSIS
Searches file contents with advanced features beyond grep.
.DESCRIPTION
A powerful cross-platform file search utility that extends beyond standard grep functionality.
Provides regex pattern matching, context lines, file filtering, colorized output, and
performance optimizations for searching large codebases.
Key features beyond grep:
- Context lines (before/after matches)
- Colorized and formatted output for readability
- Multiple path inputs and glob patterns
- File filtering by extension, size, and modification date
- Exclude patterns for files and directories
- Count-only mode for statistics
- Simple output mode for pipelines and scripting
- Line number display and match highlighting
- Recursive directory search with depth control
- Binary file detection and skipping
- Performance optimizations for large file sets
ALIASES:
The 'search' alias is created only if it doesn't already exist in the current environment.
.PARAMETER Pattern
The search pattern. Supports regular expressions by default.
Use -Literal for exact string matching.
.PARAMETER Path
One or more paths to search. Accepts file paths, directory paths, and wildcards.
If a directory is specified, searches only files in that directory unless -Recurse is used.
Supports pipeline input.
.PARAMETER Literal
Treat the Pattern as a literal string instead of a regular expression.
Special regex characters will be escaped automatically.
.PARAMETER CaseInsensitive
Perform case-insensitive pattern matching. By default, matching is case-sensitive.
When used with -IncludeCaseVariations, the pattern is automatically converted to match
variations with different separators. For example, 'userName' will match 'USERNAME',
'user_name', 'user-name', 'UserName', etc.
When used without -IncludeCaseVariations, only alphabetic case is ignored. Separators
(underscores, hyphens, spaces) must match exactly unless you use a regex pattern.
.PARAMETER Context
Number of context lines to show before and after each match.
Alias: -C
.PARAMETER Before
Number of context lines to show before each match.
Alias: -B
.PARAMETER After
Number of context lines to show after each match.
Alias: -A
.PARAMETER Include
File name patterns to include (e.g., '*.ps1', '*.txt').
Supports multiple patterns as an array.
.PARAMETER Exclude
File name patterns to exclude (e.g., '*.log', 'temp*').
Supports multiple patterns as an array.
.PARAMETER ExcludeDirectory
Directory names or wildcard patterns to exclude from recursive search
(e.g., '.git', 'node_modules', 'build*').
Exclusion is applied to directory path segments, so a pattern like 'src'
excludes '/project/src/*' but not '/project/src-utils/*' unless you use a wildcard.
.PARAMETER MaxDepth
Maximum directory depth for recursive search when -Recurse is specified.
.PARAMETER MaxFileSizeMB
Maximum file size to search (in MB). Files larger than this are skipped.
Default is 100MB.
.PARAMETER CountOnly
Only display count of matches per file instead of the actual matches.
Useful for quickly finding which files contain matches.
.PARAMETER FilesOnly
Only display file names that contain matches, not the matches themselves.
Similar to grep -l.
.PARAMETER Simple
Use simple output format suitable for pipelines and scripting.
Outputs PSCustomObjects instead of formatted text.
.PARAMETER Recurse
Search subdirectories recursively when Path points to a directory.
.PARAMETER NoLineNumber
Do not display line numbers in the output.
.PARAMETER IncludeCaseVariations
When enabled with -CaseInsensitive, groups and displays the different case variations
found for the search pattern across different naming conventions. This is useful for
identifying naming inconsistencies across a codebase.
The pattern is automatically converted to be separator-aware. For example, searching for
'userName' will find: 'userName', 'UserName', 'USERNAME', 'user_name', 'USER_NAME',
'user-name', 'USER-NAME', 'user name', 'USER NAME', etc.
The output includes:
- Total unique case variations found
- Count of each variation
- Files where each variation appears
Case patterns detected:
- ALL CAPS (USERNAME)
- Title Case (User Name)
- lowercase (username)
- First capital (Username)
- camelCase (userName)
- PascalCase (UserName)
- snake_case (user_name)
- SCREAMING_SNAKE_CASE (USER_NAME)
- kebab-case (user-name)
- SCREAMING-KEBAB-CASE (USER-NAME)
How it works: The pattern is split into words based on camelCase/PascalCase boundaries or
existing separators, then reconstructed as a regex that matches any combination of
separators (spaces, underscores, hyphens) between words.
Note: Requires -CaseInsensitive to be enabled. Cannot be used with -CountOnly, -FilesOnly,
-Context, -Before, or -After (context parameters are not applicable to variation summaries).
.EXAMPLE
PS > Search-FileContent -Pattern 'function' -Path ./Functions -Recurse
/Users/jon/Functions/Utils.ps1
42:function Get-Something {
58:function Set-Value {
/Users/jon/Functions/Helper.ps1
15:function Test-Connection {
Searches for 'function' in all files within the Functions directory recursively.
Output is colorized with file paths, line numbers, and highlighted matches.
.EXAMPLE
PS > Search-FileContent -Pattern 'TODO' -Path . -Include '*.ps1' -Context 2 -Recurse
/Users/jon/script.ps1
18- # Get user input
19- $name = Read-Host 'Name'
20: # TODO: Add validation
21- $result = Process-Name $name
22- return $result
Searches for 'TODO' in PowerShell files with 2 lines of context before and after.
Context lines are shown with '-' and matches with ':' after line numbers.
.EXAMPLE
PS > Search-FileContent -Pattern 'error' -Path ./logs -CaseInsensitive -CountOnly -Recurse
/var/logs/app.log: 23 matches
/var/logs/system.log: 5 matches
/var/logs/debug.log: 142 matches
Case-insensitive search for 'error' showing only match counts per file.
.EXAMPLE
PS > Search-FileContent -Pattern '\b\d{3}-\d{4}\b' -Path . -Include '*.txt' -Recurse
Searches for phone number patterns (XXX-XXXX) in text files using regex.
.EXAMPLE
PS > Get-ChildItem *.cs | Search-FileContent -Pattern 'class\s+\w+' -Simple
Path LineNumber Line Match
---- ---------- ---- -----
/src/Models/User.cs 12 public class UserModel { class UserModel
/src/Models/Product.cs 8 public class ProductModel { class ProductModel
/src/Services/Auth.cs 25 internal class AuthService { class AuthService
Searches C# files from pipeline for class declarations, outputting PSCustomObjects.
Perfect for further processing in pipelines or scripts.
.EXAMPLE
PS > Search-FileContent -Pattern 'import' -Path ./src -ExcludeDirectory 'node_modules','.git' -FilesOnly -Recurse
/src/app.js
/src/utils/helpers.js
/src/components/Header.jsx
/src/services/api.js
Finds files containing 'import', excluding common directories, showing only filenames.
Similar to 'grep -l' for quickly identifying which files match.
.EXAMPLE
PS > Search-FileContent -Pattern 'password' -Path . -Before 1 -After 3 -Include '*.config' -Recurse
Searches config files with 1 line before and 3 lines after each match.
.EXAMPLE
PS > Search-FileContent -Pattern 'userName' -Path ./src -CaseInsensitive -IncludeCaseVariations -Recurse
Case Variations Found: 6 unique patterns
USER_NAME (SCREAMING_SNAKE_CASE) - 15 occurrences
/src/constants.py (10)
/src/config.js (5)
userName (camelCase) - 12 occurrences
/src/auth.js (7)
/src/profile.js (5)
UserName (PascalCase) - 8 occurrences
/src/models.ts (8)
user_name (snake_case) - 5 occurrences
/src/database.py (5)
user-name (kebab-case) - 3 occurrences
/src/styles.css (3)
username (lowercase) - 2 occurrences
/src/legacy.php (2)
Searches for 'userName' and automatically finds all case and separator variations.
Pattern is intelligently converted to match userName, user_name, user-name, UserName, etc.
Helps identify naming inconsistencies across different files and coding conventions.
.EXAMPLE
PS > Search-FileContent -Pattern 'apikey' -Path . -CaseInsensitive -IncludeCaseVariations -Simple -Recurse
Variation CasePattern Count Files
--------- ----------- ----- -----
API_KEY SCREAMING_SNAKE_CASE 15 {config.py, settings.py}
apiKey camelCase 8 {app.js, utils.js}
ApiKey PascalCase 2 {Models.cs}
Simple output mode showing case variations as structured objects for pipeline processing.
.EXAMPLE
PS > Search-FileContent -Pattern 'test' -Path ./src, ./lib, ./tests -Literal -Recurse
Searches multiple directories for literal string 'test' (not regex).
.EXAMPLE
PS > Search-FileContent -Pattern 'console\.log' -Path ./src -Include '*.ts' -FilesOnly -Recurse | ForEach-Object { Write-Host "Remove logging in $($_.Path)" }
Quickly enumerates files that still contain debug logging before promoting a build.
.OUTPUTS
PSCustomObject (when -Simple is used)
Returns objects with properties: Path, LineNumber, Line, Match
Formatted text (default)
Colorized output showing file paths, line numbers, and matched content
.NOTES
- Binary files are automatically detected and skipped
- Large files (>100MB by default) are skipped for performance
- Use -Simple for programmatic processing of results
- Exclude common directories like .git, node_modules for better performance
- Context lines are marked with '--' separator in formatted output
- Directory paths are non-recursive by default. Use -Recurse when you want to traverse subdirectories.
Author: Jon LaBelle
License: MIT
Source: https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/Utilities/Search-FileContent.ps1
.LINK
https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/Utilities/Search-FileContent.ps1
#>
[CmdletBinding(DefaultParameterSetName = 'Default')]
[OutputType([PSCustomObject])]
param(
[Parameter(Mandatory, Position = 0)]
[ValidateNotNullOrEmpty()]
[String]$Pattern,
[Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, Position = 1)]
[Alias('FullName', 'FilePath', 'PSPath')]
[ValidateNotNullOrEmpty()]
[String[]]$Path = (Get-Location),
[Parameter()]
[Switch]$Literal,
[Parameter()]
[Switch]$CaseInsensitive,
[Parameter()]
[Alias('C')]
[ValidateRange(0, 100)]
[Int]$Context,
[Parameter()]
[Alias('B')]
[ValidateRange(0, 100)]
[Int]$Before,
[Parameter()]
[Alias('A')]
[ValidateRange(0, 100)]
[Int]$After,
[Parameter()]
[String[]]$Include,
[Parameter()]
[String[]]$Exclude,
[Parameter()]
[String[]]$ExcludeDirectory = @('.git', '.svn', 'node_modules'),
[Parameter()]
[ValidateRange(1, 100)]
[Int]$MaxDepth,
[Parameter()]
[ValidateRange(1, 10240)]
[Int]$MaxFileSizeMB = 100,
[Parameter()]
[Switch]$CountOnly,
[Parameter()]
[Switch]$FilesOnly,
[Parameter()]
[Switch]$Simple,
[Parameter()]
[Switch]$Recurse,
[Parameter()]
[Switch]$NoLineNumber,
[Parameter()]
[Switch]$IncludeCaseVariations
)
begin
{
Write-Verbose 'Initializing Search-FileContent'
# Detect platform once for case-sensitive/insensitive path comparisons.
$isWindowsPlatform = if ($PSVersionTable.PSVersion.Major -lt 6) { $true } else { $IsWindows }
$filePathComparer = if ($isWindowsPlatform) { [System.StringComparer]::OrdinalIgnoreCase } else { [System.StringComparer]::Ordinal }
# Helper function to convert a pattern to separator-aware regex
function Convert-ToSeparatorAwarePattern
{
param([String]$Pattern)
# Split pattern into words based on camelCase, PascalCase, or existing separators
$words = @()
$currentWord = ''
for ($i = 0; $i -lt $Pattern.Length; $i++)
{
$char = $Pattern[$i]
# Check if this is a separator
if ($char -match '[\s_-]')
{
if ($currentWord.Length -gt 0)
{
$words += $currentWord
$currentWord = ''
}
continue
}
# Check for camelCase/PascalCase boundary (lowercase followed by uppercase)
if ($i -gt 0 -and
[char]::IsLower($Pattern[$i - 1]) -and
[char]::IsUpper($char))
{
$words += $currentWord
$currentWord = $char
}
# Check for acronym boundary (multiple uppercase followed by lowercase)
elseif ($i -gt 1 -and
[char]::IsUpper($Pattern[$i - 2]) -and
[char]::IsUpper($Pattern[$i - 1]) -and
[char]::IsLower($char))
{
# Move last char of previous word to current word
$lastChar = $currentWord[$currentWord.Length - 1]
$currentWord = $currentWord.Substring(0, $currentWord.Length - 1)
if ($currentWord.Length -gt 0)
{
$words += $currentWord
}
$currentWord = $lastChar + $char
}
else
{
$currentWord += $char
}
}
# Add the last word
if ($currentWord.Length -gt 0)
{
$words += $currentWord
}
# If no words were detected, treat entire pattern as single word
if ($words.Count -eq 0)
{
$words = @($Pattern)
}
# Build regex pattern with optional separators between words
$escapedWords = $words | ForEach-Object { [Regex]::Escape($_) }
$regexPattern = $escapedWords -join '[\s_-]*'
Write-Verbose "Converted pattern '$Pattern' to separator-aware regex: '$regexPattern'"
Write-Verbose "Detected words: $($words -join ', ')"
return $regexPattern
}
# Validate parameter combinations
if ($IncludeCaseVariations)
{
if (-not $CaseInsensitive)
{
throw 'IncludeCaseVariations requires CaseInsensitive to be enabled'
}
if ($CountOnly)
{
throw 'IncludeCaseVariations cannot be used with CountOnly'
}
if ($FilesOnly)
{
throw 'IncludeCaseVariations cannot be used with FilesOnly'
}
if ($Context -gt 0 -or $Before -gt 0 -or $After -gt 0)
{
throw 'IncludeCaseVariations cannot be used with Context, Before, or After parameters (context is not applicable to variation summaries)'
}
}
# Context handling - Context overrides Before/After if specified
if ($PSBoundParameters.ContainsKey('Context'))
{
$Before = $Context
$After = $Context
}
else
{
if (-not $PSBoundParameters.ContainsKey('Before')) { $Before = 0 }
if (-not $PSBoundParameters.ContainsKey('After')) { $After = 0 }
}
# Prepare regex options
$regexOptions = [System.Text.RegularExpressions.RegexOptions]::None
if ($CaseInsensitive)
{
$regexOptions = $regexOptions -bor [System.Text.RegularExpressions.RegexOptions]::IgnoreCase
}
# Escape pattern for literal matching or convert to separator-aware pattern
$searchPattern = if ($IncludeCaseVariations)
{
# For case variations, automatically convert to separator-aware pattern
Convert-ToSeparatorAwarePattern -Pattern $Pattern
}
elseif ($Literal)
{
[Regex]::Escape($Pattern)
}
else
{
$Pattern
}
# Compile regex for performance
try
{
$regex = [Regex]::new($searchPattern, $regexOptions)
}
catch
{
throw "Invalid regex pattern '$Pattern': $($_.Exception.Message)"
}
# Maximum file size in bytes
$maxFileSizeBytes = $MaxFileSizeMB * 1MB
# Color codes for formatted output (only if not Simple mode)
if (-not $Simple -and -not $FilesOnly)
{
$colorReset = "`e[0m"
$colorFile = "`e[90m" # Dark gray for file paths
$colorLineNum = "`e[90m" # Dark gray for line numbers
$colorMatch = "`e[96m" # Bright cyan for matches
$colorContext = "`e[90m" # Gray for context
}
# Function to check if file is binary
function Test-BinaryFile
{
param([String]$FilePath)
try
{
# First check file extension for obvious binary files
$extension = [System.IO.Path]::GetExtension($FilePath).ToLower()
$binaryExtensions = @(
# Executables and Libraries
'.exe', '.dll', '.so', '.dylib', '.a', '.lib', '.obj', '.o',
# Archives
'.zip', '.7z', '.rar', '.tar', '.gz', '.bz2', '.xz', '.iso',
# Images
'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.ico', '.webp',
# Audio/Video
'.mp3', '.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.wav',
# Documents
'.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx',
# Other
'.pyc', '.class', '.sqlite', '.db'
)
if ($binaryExtensions -contains $extension)
{
Write-Verbose "Skipping binary file by extension: $FilePath"
return $true
}
# Content-based detection using streaming
$buffer = New-Object byte[] 8192
$stream = [System.IO.File]::OpenRead($FilePath)
try
{
$bytesRead = $stream.Read($buffer, 0, $buffer.Length)
if ($bytesRead -eq 0)
{
return $false # Empty file is not binary
}
# Check for null bytes - if more than 10% are null, likely binary
$nullByteCount = 0
for ($i = 0; $i -lt $bytesRead; $i++)
{
if ($buffer[$i] -eq 0)
{
$nullByteCount++
}
}
if ($nullByteCount -gt ($bytesRead * 0.1))
{
Write-Verbose "Skipping binary file (null byte ratio): $FilePath"
return $true
}
# Check ratio of printable characters
$printableCount = 0
for ($i = 0; $i -lt $bytesRead; $i++)
{
$byte = $buffer[$i]
# Count ASCII printable and common whitespace
if (($byte -ge 32 -and $byte -le 126) -or $byte -eq 9 -or $byte -eq 10 -or $byte -eq 13)
{
$printableCount++
}
}
$printableRatio = $printableCount / $bytesRead
if ($printableRatio -lt 0.60)
{
Write-Verbose "Skipping binary file (low printable ratio): $FilePath"
return $true
}
return $false
}
finally
{
$stream.Close()
}
}
catch
{
Write-Verbose "Error checking if file is binary: $FilePath"
return $true # Assume binary if we can't read it
}
}
# Function to get files to search
function Test-IsExcludedDirectoryPath
{
param(
[String]$FilePath,
[String[]]$DirectoryPatterns
)
if (-not $DirectoryPatterns -or $DirectoryPatterns.Count -eq 0)
{
return $false
}
$directoryPath = [System.IO.Path]::GetDirectoryName($FilePath)
if ([String]::IsNullOrEmpty($directoryPath))
{
return $false
}
$pathSegments = $directoryPath -split '[\\/]'
foreach ($segment in $pathSegments)
{
if ([String]::IsNullOrWhiteSpace($segment))
{
continue
}
foreach ($pattern in $DirectoryPatterns)
{
if ($segment -like $pattern)
{
return $true
}
}
}
return $false
}
# Function to get files to search
function Get-SearchFile
{
param(
[String]$SearchPath,
[String[]]$IncludePatterns,
[String[]]$ExcludePatterns,
[String[]]$ExcludeDirs,
[Int]$Depth,
[Bool]$Recurse
)
$resolvedPath = $PSCmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath($SearchPath)
# Check if path exists
if (-not (Test-Path -LiteralPath $resolvedPath))
{
Write-Warning "Path not found: $SearchPath"
return
}
$item = Get-Item -LiteralPath $resolvedPath -Force
if ($item.PSIsContainer)
{
# Directory - get files
$getChildItemParams = @{
LiteralPath = $resolvedPath
File = $true
Force = $true
ErrorAction = 'SilentlyContinue'
}
if ($Recurse)
{
$getChildItemParams['Recurse'] = $true
if ($Depth)
{
$getChildItemParams['Depth'] = $Depth
}
}
$files = Get-ChildItem @getChildItemParams
$filteredFiles = [System.Collections.Generic.List[System.IO.FileInfo]]::new()
foreach ($candidateFile in $files)
{
$fileName = $candidateFile.Name
# Apply include filter.
if ($IncludePatterns)
{
$includeMatch = $false
foreach ($pattern in $IncludePatterns)
{
if ($fileName -like $pattern)
{
$includeMatch = $true
break
}
}
if (-not $includeMatch)
{
continue
}
}
# Apply exclude filter.
if ($ExcludePatterns)
{
$excludeMatch = $false
foreach ($pattern in $ExcludePatterns)
{
if ($fileName -like $pattern)
{
$excludeMatch = $true
break
}
}
if ($excludeMatch)
{
continue
}
}
# Apply directory exclusion against directory path segments
# to avoid false positives from plain substring matching.
if ($ExcludeDirs -and (Test-IsExcludedDirectoryPath -FilePath $candidateFile.FullName -DirectoryPatterns $ExcludeDirs))
{
continue
}
$filteredFiles.Add($candidateFile)
}
$filteredFiles
}
else
{
# Single file
$item
}
}
# Helper function to detect case pattern of a string
function Get-CasePattern
{
param([String]$Text)
if ([string]::IsNullOrEmpty($Text))
{
return 'Unknown'
}
# Helper to check if text contains underscores and is consistent case
$hasUnderscores = $Text -match '_'
$hasHyphens = $Text -match '-'
$hasSpaces = $Text -match '\s'
# All uppercase
if ($Text -ceq $Text.ToUpper())
{
if ($hasUnderscores)
{
return 'SCREAMING_SNAKE_CASE'
}
elseif ($hasHyphens)
{
return 'SCREAMING-KEBAB-CASE'
}
elseif ($hasSpaces)
{
return 'ALL CAPS'
}
else
{
return 'UPPERCASE'
}
}
# All lowercase
if ($Text -ceq $Text.ToLower())
{
if ($hasUnderscores)
{
return 'snake_case'
}
elseif ($hasHyphens)
{
return 'kebab-case'
}
elseif ($hasSpaces)
{
return 'lowercase'
}
else
{
return 'lowercase'
}
}
# Check for separators (if mixed case with separators)
if ($hasUnderscores)
{
$letters = $Text -replace '_', ''
if ($letters -and (($letters -ceq $letters.ToLower()) -or ($letters -ceq $letters.ToUpper())))
{
return 'snake_case (mixed)'
}
}
if ($hasHyphens)
{
$letters = $Text -replace '-', ''
if ($letters -and (($letters -ceq $letters.ToLower()) -or ($letters -ceq $letters.ToUpper())))
{
return 'kebab-case (mixed)'
}
}
# Check for camelCase or PascalCase (no spaces/separators, mixed case)
if (-not $hasSpaces -and -not $hasUnderscores -and -not $hasHyphens)
{
# Look for lowercase followed by uppercase
$hasCamelTransition = $false
for ($i = 0; $i -lt $Text.Length - 1; $i++)
{
if ([char]::IsLower($Text[$i]) -and [char]::IsUpper($Text[$i + 1]))
{
$hasCamelTransition = $true
break
}
}
if ($hasCamelTransition)
{
if ([char]::IsUpper($Text[0]))
{
return 'PascalCase'
}
else
{
return 'camelCase'
}
}
}
# Check for Title Case (spaces with each word capitalized)
if ($hasSpaces)
{
$words = $Text -split '\s+'
$allWordsCapitalized = $true
foreach ($word in $words)
{
if ($word.Length -gt 0 -and [char]::IsLower($word[0]))
{
$allWordsCapitalized = $false
break
}
}
if ($allWordsCapitalized -and $words.Count -gt 1)
{
return 'Title Case'
}
}
# First letter capitalized only
if ($Text.Length -gt 0 -and [char]::IsUpper($Text[0]))
{
$restLower = $true
for ($i = 1; $i -lt $Text.Length; $i++)
{
if ([char]::IsUpper($Text[$i]))
{
$restLower = $false
break
}
}
if ($restLower)
{
return 'First Capital'
}
}
return 'Mixed Case'
}
# Function to search a single file
function Search-SingleFile
{
param(
[System.IO.FileInfo]$File,
[Regex]$Regex,
[Int]$BeforeLines,
[Int]$AfterLines,
[Int64]$MaxSize
)
# Check file size
if ($File.Length -gt $MaxSize)
{
Write-Verbose "Skipping large file ($(($File.Length / 1MB).ToString('F2'))MB): $($File.FullName)"
return
}
# Check if binary
if (Test-BinaryFile -FilePath $File.FullName)
{
Write-Verbose "Skipping binary file: $($File.FullName)"
return
}
try
{
$matchCount = 0
$results = [System.Collections.Generic.List[object]]::new()
$hasContext = $BeforeLines -gt 0 -or $AfterLines -gt 0
if (-not $hasContext)
{
# Stream lines when context is not requested to reduce memory use
# for large files and large file sets.
$lineNumber = 0
foreach ($line in [System.IO.File]::ReadLines($File.FullName))
{
$lineNumber++
if ($Regex.IsMatch($line))
{
$matchCount++
$matchValue = $Regex.Match($line).Value
$contextLines = @(
[PSCustomObject]@{
LineNumber = $lineNumber
Content = $line
IsMatch = $true
}
)
$results.Add([PSCustomObject]@{
Path = $File.FullName
LineNumber = $lineNumber
Line = $line
Match = $matchValue
Context = $contextLines
})
}
}
}
else
{
# Context output requires random access to surrounding lines.
$lines = [System.IO.File]::ReadAllLines($File.FullName)
for ($i = 0; $i -lt $lines.Count; $i++)
{
$line = $lines[$i]
$lineNumber = $i + 1
if ($Regex.IsMatch($line))
{
$matchCount++
# Store match with context
$contextStart = [Math]::Max(0, $i - $BeforeLines)
$contextEnd = [Math]::Min($lines.Count - 1, $i + $AfterLines)
$contextLines = [System.Collections.Generic.List[object]]::new()
for ($c = $contextStart; $c -le $contextEnd; $c++)
{
$contextLines.Add([PSCustomObject]@{
LineNumber = $c + 1
Content = $lines[$c]
IsMatch = ($c -eq $i)
})
}
$matchValue = $Regex.Match($line).Value
$results.Add([PSCustomObject]@{
Path = $File.FullName
LineNumber = $lineNumber
Line = $line
Match = $matchValue
Context = @($contextLines)
})
}
}
}
# Return file info with results
[PSCustomObject]@{
Path = $File.FullName
MatchCount = $matchCount
Matches = @($results)
}
}
catch
{
Write-Verbose "Error reading file $($File.FullName): $($_.Exception.Message)"
return
}
}
# Collection for all files to process