Powershell: Search directories and subdirectories for files with specific content
I’d like to share a small PowerShell script that scans all subdirectories for specific files (for example, *.yaml and *.yml) and searches them for a specific string (e.g., “ansible.builtin.template”). The result is returned with the location (name and path of the file, and line number of the search string in the file).
What it does:
- Recursively searches all .yaml and .yml files starting from the current directory (.).
- Searches for the string service time in each file.
- Prints the file, line number, and line contents for each match.
# String to search for
$searchterm= "ansible.builtin.template"
# Search all .yaml and .yml files recursively
Get-ChildItem -Path . -Recurse -Include *.yaml, *.yml -File | ForEach-Object {
$Datei = $_.FullName
# Search the file contents line by line
Select-String -Path $Datei -Pattern $searchterm| ForEach-Object {
[PSCustomObject]@{
Datei = $_.Path
Zeile = $_.LineNumber
Inhalt = $_.Line.Trim()
}
}
}
Sometimes I want to save my results to a file and explore them further. To save the results to a CSV file, adapt the script as follows:
$results= Get-ChildItem -Path . -Recurse -Include *.yaml, *.yml -File | ForEach-Object {
$Datei = $_.FullName
Select-String -Path $Datei -Pattern $Suchbegriff | ForEach-Object {
[PSCustomObject]@{
Datei = $_.Path
Zeile = $_.LineNumber
Inhalt = $_.Line.Trim()
}
}
}
$results | Export-Csv -Path "searchresults.csv" -NoTypeInformation -Encoding UTF8