jgt05
jgt05

Reputation: 27

How to search content in files in Powershell

I want to make a dynamic function that searches for the requested $ErrorCode within the files inputted and eventually copy the files with the error to another folder.

Right now, my code takes only one file and returns the sentence of where the $Error_Code was found. I want to search through multiple files and return the name of the file that have the $ErrorCode.

function SearchError{

    Param (
        [Parameter (Mandatory=$true)] [STRING] $SourcePath,
        [Parameter (Mandatory=$true)] [STRING] $SourceFile,
        [Parameter (Mandatory=$true)] [STRING] $ErrorCode,
        [Parameter (Mandatory=$true)] [STRING] $FileType
       # [Parameter (Mandatory=$true)] [STRING] $DestPath


        )  
    $TargetPath = "$($SourcePath)\$($SourceFile)"
    #Return $TargetPath

    $DestinationPath = "$($DestPath)"
    #Return $DestinationPath 


    #foreach($error in $TargetPath) {

    Get-ChildItem $TargetPath | Select-String -pattern $ErrorCode 

}
SearchError 

Upvotes: 2

Views: 2106

Answers (1)

mklement0
mklement0

Reputation: 437708

  • Select-String's output objects - which are of type [Microsoft.PowerShell.Commands.MatchInfo] - have a .Path property that reflects the input file path.

  • Adding the -List switch to Select-String makes it stop searching after the first match in the file, so you'll get exactly 1 output object for each file in which at least 1 match was found.

Therefore, the following outputs only the paths of the input files in which at least 1 match was found:

Get-ChildItem $TargetPath |
  Select-String -List -Pattern $ErrorCode | ForEach-Object Path

Note: -Pattern supports an array of regex patterns, so if you define your $ErrorCode parameter as [string[]], files that have any one of the patterns will match; use -SimpleMatch instead of -Pattern to search by literal substrings instead.


Re:

eventually copy the files with the error to another folder

Simply appending | Copy-Item -Destination $DestPath to the above command should do.

Re:

I want to search through multiple files

Depending on your needs, you can make your $SourcePath and $SourceFile parameters array-valued ([string[]]) and / or pass wildcard expressions as arguments.

Upvotes: 1

Related Questions