SHARE
TWEET

Find-InFile

a guest Jul 15th, 2019 92 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <#
  2. .Synopsis
  3. Find content in file and return line number and matching line(s)
  4. .DESCRIPTION
  5. Find content in file and return line number and matching line(s)
  6. .EXAMPLE
  7. Find-InFile -File C:\test.txt -Query "Find This Text"
  8. #>
  9.  
  10. function Find-InFile {
  11.     [CmdletBinding()]
  12.     param (
  13.         [Parameter(Mandatory = $true,
  14.                     ValueFromPipelineByPropertyName)]
  15.         [string[]]$FullName,
  16.         [Parameter(Mandatory = $true)]
  17.         [string]$Query
  18.     )
  19.  
  20.     begin {
  21.         $SearchResults = @()
  22.     }
  23.  
  24.     Process {
  25.         foreach ($File in $FullName){
  26.             $contents = Get-Content -LiteralPath $File
  27.             $search = "*" + $Query + "*"
  28.             $contents | ForEach-Object {
  29.                 if ($_ -like $search){
  30.                     $SearchResults += [pscustomobject]@{
  31.                         LineNumber = $_.ReadCount
  32.                         FileName = $File
  33.                         Line = $_.Trim()
  34.                     }
  35.                 } else {
  36.                     # Write-Host -ForegroundColor Red "No search results"
  37.                 } #
  38.             } # Foreach-Object
  39.         } # foreach ($File in $FullName){
  40.  
  41.         $SearchResults
  42.    
  43.     } # process
  44.  
  45. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top