Mike P Mike P - 1 year ago 88
PowerShell Question

How to look for a string within the contents of each file on a list? -Powershell

I have the following line which gives me a list of files.

{Get-ChildItem -Recurse -Force $filePath | sort-object -property CreationTime -descending | where { $_.CreationTime.dayofyear -eq $today } | Where-Object { ($_.PSIsContainer -eq $false) -and ( $_.Name -like "*FILE1*" -or $_.Name -like "*FILE2*" -or $_.Name -like "*FILE3*") } | Select-Object Name,CreationTime,CreationDay | Format-Table -AutoSize * }

Here's my results:

Name CreationTime

  • FILE1.022291 8/25/2016 8:25:07 AM

  • FILE2.022285 8/25/2016 2:25:10 AM

  • FILE3.022281 8/25/2016 2:25:08 AM

I'd like to look for two specific strings within each file of the results, and if any of the specific strings are found, display the whole line that the string is on below each result.

Here's what I'm hoping it can look like

Name CreationTime

  • FILE1.022291 8/25/2016 8:25:07 AM


  • FILE2.022285 8/25/2016 2:25:10 AM


  • FILE3.022281 8/25/2016 2:25:08 AM


Any help would be greatly appreciated. I'm somewhat new to Powershell so I'll do my best to help with any questions.

Answer Source

You can use Select-String for that info. Just get the file objects filter for the date you are looking for, then use Select-String. Select-String's out is FileName:LineNumber:Match.

PS> gci -File -Path $filePath file* | ? creationtime -gt (get-date).AddMinutes(-30) | Select-String -Pattern "SpecificString1|SpecificString2"


And here is some formatting using named expressions in the select statement.

PS> gci -File -Path $filePath file* | ? creationtime -gt (get-date).AddMinutes(-30) | Select @{n='StringFound';e={$_ | Select-String -Pattern "SpecificString1|SpecificString2"}}, CreationTime;

StringFound                            CreationTime
-----------                            ------------
C:\temp\FILE1.022291:2:SpecificString1 8/25/2016 1:09:50 PM
C:\temp\FILE2.022285:4:SpecificString2 8/25/2016 1:09:50 PM
C:\temp\FILE3.022281:1:SpecificString1 8/25/2016 1:09:50 PM

Here is working with the select-string output:

 PS> gci -File -Path $filePath file* | ? creationtime -gt (get-date).AddMinutes(-600) | Select-String -Pattern "Speci
ficString1|SpecificString2" -AllMatches | select LineNumber, FileName, Line, matches

LineNumber Filename     Line                       Matches
---------- --------     ----                       -------
         2 FILE1.022291 SpecificString1            {SpecificString1}
         4 FILE1.022291 sfdgdsgsdf SpecificString2 {SpecificString2}
         6 FILE1.022291 SpecificString2            {SpecificString2}
         4 FILE2.022285 SpecificString2            {SpecificString2}
         1 FILE3.022281 SpecificString1            {SpecificString1}   
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download