PowerShell/Scripts/search-files.ps1

38 lines
988 B
PowerShell
Raw Normal View History

2021-08-26 10:46:12 +02:00
<#
2021-07-13 21:10:02 +02:00
.SYNOPSIS
search-files.ps1 [<pattern>] [<path>]
.DESCRIPTION
2021-08-29 17:50:03 +02:00
Searches for the given pattern in the given files.
2021-07-13 21:10:02 +02:00
.EXAMPLE
PS> .\search-files.ps1 UFO C:\Temp\*.txt
2021-08-29 17:50:03 +02:00
.NOTES
Author: Markus Fleschutz · License: CC0
2021-07-13 21:10:02 +02:00
.LINK
https://github.com/fleschutz/PowerShell
2020-12-29 15:14:21 +01:00
#>
2020-12-29 12:03:53 +01:00
2021-07-15 15:51:22 +02:00
param([string]$Pattern = "", [string]$Path = "")
2020-12-29 12:03:53 +01:00
2021-01-02 14:02:16 +01:00
function ListScripts { param([string]$Pattern, [string]$Path)
$List = Select-String -Path $Path -Pattern "$Pattern"
foreach ($Item in $List) {
New-Object PSObject -Property @{
'Path' = "$($Item.Path)"
'Line' = "$($Item.LineNumber)"
'Text' = "$($Item.Line)"
}
}
write-output "(pattern found at $($List.Count) locations)"
}
2020-12-29 12:03:53 +01:00
try {
2021-07-15 15:51:22 +02:00
if ($Pattern -eq "" ) { $Pattern = read-host "Enter search pattern" }
if ($Path -eq "" ) { $Path = read-host "Enter path to files" }
2021-01-02 14:02:16 +01:00
ListScripts $Pattern $Path | format-table -property Path,Line,Text
2020-12-29 12:03:53 +01:00
exit 0
} catch {
2021-05-02 21:30:48 +02:00
write-error "⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
2020-12-29 12:03:53 +01:00
exit 1
}