how to Search-Keywords in files – PowerShell function

function Search-File{
PARAM(
[STRING[]]$Path = $pwd,
[STRING[]]$Include = “*.ps1”,
[STRING[]]$KeyWord = (Read-Host “Keyword?”),
[SWITCH]$ListView
)

<#
Descrition: This function allows you to search a folder and it’s sub directories for files containing a keyword.

Exampls: Search-File -Path C:\temp -Include “*.pdf” -KeyWord “nagios”

Date: Sunday, April 3, 2016 10:03:16 AM

The function uses three parameters and one switch.

Parameters

-Path
By default, the path will use your present working directory ($pwd). The search path is always recursive.

-Include
By default the include is set to “*.ps1”. The value for this parameter filters by file name.
Examples : -Include “*.log” or “Servers*.log”

-Keyword
If no value is provided you will be prompted with “Keyword?:”.
This parameter invokes “Search-String -Simplematch $Keyword”; I sometimes search for regular expressions, but a switch could be added to the function to utilize “Search-String -Pattern” allowing use of regular expressions in the keyword search.
Uses a simple match rather than a regular expression match. In a simple match, Select-String searches the input for the text in the Pattern parameter. It does not interpret the value of the Pattern parameter as a regular expression statement.

Switches

-ListView
While the default formatting neatly groups matched lines under the filename, the line is truncated. If you want to see the full line containing the match, use this switch.

#>

Get-ChildItem -path $Path -Include $Include -Recurse | `
sort Directory,CreationTime | `
Select-String -simplematch $KeyWord -OutVariable Result | `
Out-Null

IF ($ListView) {
$Result | Format-List -Property Path,LineNumber,Line
}
ELSE {
$Result | Format-Table -GroupBy Path -Property LineNumber,Line -AutoSize
}

}

Source: Search-Scripts – PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources