PowerShell/scripts/search-files.ps1

41 lines
1.4 KiB
PowerShell
Raw Normal View History

2023-10-31 13:03:45 +01:00
<#
2021-07-13 21:10:02 +02:00
.SYNOPSIS
2024-08-13 14:04:34 +02:00
Searches for text in files
2021-10-04 21:29:23 +02:00
.DESCRIPTION
2024-08-13 14:04:34 +02:00
This PowerShell script searches for the given text pattern in the given files.
2024-05-08 12:58:57 +02:00
.PARAMETER textPattern
Specifies the text pattern to search for
.PARAMETER filePattern
Specifies the files to search
2021-07-13 21:10:02 +02:00
.EXAMPLE
2024-05-15 15:41:03 +02:00
PS> ./search-files.ps1 UFO *.ps1
FILE LINE
---- ----
/home/Markus/PowerShell/scripts/check-month.ps1 17: $MonthName = (Get-Date -UFormat %B)
2024-05-08 12:58:57 +02:00
...
2021-07-13 21:10:02 +02:00
.LINK
https://github.com/fleschutz/PowerShell
2022-01-30 10:49:30 +01:00
.NOTES
2022-09-06 21:42:04 +02:00
Author: Markus Fleschutz | License: CC0
2020-12-29 15:14:21 +01:00
#>
2020-12-29 12:03:53 +01:00
2024-05-08 12:58:57 +02:00
param([string]$textPattern = "", [string]$filePattern = "")
2020-12-29 12:03:53 +01:00
2024-08-13 14:04:34 +02:00
function ListLocations { param([string]$textPattern, [string]$filePattern)
$list = Select-String -path $filePattern -pattern "$textPattern"
foreach($item in $list) { New-Object PSObject -Property @{ 'FILE'="$($item.Path)"; 'LINE'="$($item.LineNumber):$($item.Line)" } }
"✔️ Found $($list.Count) lines containing '$textPattern' in $filePattern."
2021-01-02 14:02:16 +01:00
}
2020-12-29 12:03:53 +01:00
try {
2024-08-13 14:04:34 +02:00
if ($textPattern -eq "" ) { $textPattern = Read-Host "Enter the text pattern, e.g. 'UFO'" }
if ($filePattern -eq "" ) { $filePattern = Read-Host "Enter the file pattern, e.g. '*.ps1'" }
2021-07-15 15:51:22 +02:00
2024-05-08 12:58:57 +02:00
ListLocations $textPattern $filePattern | Format-Table -property FILE,LINE -autoSize
2021-09-27 10:09:45 +02:00
exit 0 # success
2020-12-29 12:03:53 +01:00
} catch {
2022-04-13 12:06:32 +02:00
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
2020-12-29 12:03:53 +01:00
exit 1
}