Wednesday, December 26, 2018

Search directory and multiple file contents with Powershell

This script will search directory and file contents with Powershell




$HowManyDays = 7
$FileAge = (Get-Date).AddDays(-$HowManyDays)
$FindThis = "test"
$WhatFiles = "*.log"
$SearchWhere = ".\"

$MsgOut = 'Searching for "{0}" in {1} (files) starting in {2} for the past {3} days' -f $FindThis, $WhatFiles, $SearchWhere, $HowManyDays

#-----------------------------------------------------------[Execution]------------------------------------------------------------



Write-Host $MsgOut #  '+$WhatFiles +' starting in '+$SarchWhere
$fileList = Get-ChildItem -Path $SearchWhere -Recurse -Force -ErrorAction SilentlyContinue -Include $WhatFiles |Where-Object {$_.LastWriteTime -gt $FileAge}

#  This for each loop code "% {$i++;"$($i-1) `t $_"}" adds the line numbers to the output. Ref: https://superuser.com/questions/1182291/how-do-i-get-line-numbers-with-powershell/1272052#1272052

ForEach ($file in $filelist) { $i=1
 "Searching File ...:: "+$file.FullName
                                Get-Content $file.FullName -Force -ErrorAction SilentlyContinue | % {$i++;"$($i-1) `t $_"}| Select-String -pattern $FindThis}

No comments:

Post a Comment