|
1 | 1 | <# |
2 | 2 | .SYNOPSIS |
3 | | - Searches for a pattern in files |
| 3 | + Searches for a text pattern in files |
4 | 4 | .DESCRIPTION |
5 | | - This PowerShell script searches for a pattern in the given files. |
6 | | -.PARAMETER pattern |
7 | | - Specifies the search pattern |
8 | | -.PARAMETER files |
9 | | - Specifies the files |
| 5 | + This PowerShell script searches for the given pattern in the given files. |
| 6 | +.PARAMETER textPattern |
| 7 | + Specifies the text pattern to search for |
| 8 | +.PARAMETER filePattern |
| 9 | + Specifies the files to search |
10 | 10 | .EXAMPLE |
11 | 11 | PS> ./search-files UFO C:\Temp\*.txt |
| 12 | + ... |
| 13 | + ✔️ Found 'UFO' at 9 locations. |
12 | 14 | .LINK |
13 | 15 | https://github.com/fleschutz/PowerShell |
14 | 16 | .NOTES |
15 | 17 | Author: Markus Fleschutz | License: CC0 |
16 | 18 | #> |
17 | 19 |
|
18 | | -param([string]$pattern = "", [string]$files = "") |
| 20 | +param([string]$textPattern = "", [string]$filePattern = "") |
19 | 21 |
|
20 | 22 | function ListLocations { param([string]$Pattern, [string]$Path) |
21 | | - $List = Select-String -Path $Path -Pattern "$Pattern" |
22 | | - foreach ($Item in $List) { |
23 | | - New-Object PSObject -Property @{ |
24 | | - 'Path' = "$($Item.Path)" |
25 | | - 'Line' = "$($Item.LineNumber)" |
26 | | - 'Text' = "$($Item.Line)" |
27 | | - } |
| 23 | + $list = Select-String -path $Path -pattern "$Pattern" |
| 24 | + foreach ($item in $list) { |
| 25 | + New-Object PSObject -Property @{ 'FILE'="$($item.Path)"; 'LINE'="$($item.LineNumber):$($item.Line)" } |
28 | 26 | } |
29 | | - write-output "(found $($List.Count) locations with pattern '$pattern')" |
| 27 | + Write-Output "✔️ Found '$Pattern' at $($list.Count) locations." |
30 | 28 | } |
31 | 29 |
|
32 | 30 | try { |
33 | | - if ($pattern -eq "" ) { $pattern = read-host "Enter search pattern" } |
34 | | - if ($files -eq "" ) { $files = read-host "Enter path to files" } |
| 31 | + if ($textPattern -eq "" ) { $textPattern = Read-Host "Enter the text pattern (e.g. 'UFO')" } |
| 32 | + if ($filePattern -eq "" ) { $filePattern = Read-Host "Enter the file pattern (e.g. '*.txt')" } |
35 | 33 |
|
36 | | - ListLocations $pattern $files | format-table -property Path,Line,Text |
| 34 | + ListLocations $textPattern $filePattern | Format-Table -property FILE,LINE -autoSize |
37 | 35 | exit 0 # success |
38 | 36 | } catch { |
39 | 37 | "⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])" |
|
0 commit comments