powershellrecursionreturn-path

Return file path and context text line after recursive search


Trying to do a recursive search through all .txt files for a specific word and return the path of the file where the text was found and the context text line.

Currently using the below PowerShell script to recursively search and export to a separate file the paths of the files where the text was found and then open them to manually search for the context. The word might be found several times in file due to different context and all of them need to be reviewed.

$Path = Get-Location
$Text0 = "sometext"
$PathArray = @()
$Results0 = "$Path\$Text0.txt"

Get-ChildItem $Path -Filter "*.txt" -Recurse -Force -ErrorAction SilentlyContinue |
    Where-Object { $_.Attributes -ne "Directory" } |
    ForEach-Object {
        if (Get-Content $_.FullName | Select-String -Pattern $Text0) {
            $PathArray += $_.FullName
            $PathArray += $_.FullName
        }
    }
Write-Host "Contents of ArrayPath:"
$PathArray | ForEach-Object {$_} | Out-File $Results0 -Append 

I expect the output of "c:\folder\folder\folder\textfile.txt" (current output) to be "c:\folder\folder\folder\textfile.txt; This is the text line containing the context where sometext was found."


Solution

  • If you're on PowerShell version 3.0 or better, you can do this:

    Get-ChildItem -Path $Path -Filter "*.txt" -File -Recurse -Force |
        Select-String -Pattern $Text0 | 
        Select-Object Path, Line
    

    For PowerShell below version 3.0:

    Get-ChildItem -Path $Path -Filter "*.txt" -Recurse -Force | 
        Where-Object { !$_.PsIsContainer } |
        Select-String -Pattern $Text0 | 
        Select-Object Path, Line, LineNumber
    

    Would return something like

    Path                    Line 
    ----                    ---- 
    D:\test\blah.txt        this is the line that contains sometext.
    D:\test\anotherfile.txt sometext