powershellmonitoringstring-searchlogfile-analysis

Looking for a powershell script that takes latest txt file in directory and searches for keyword "RequriedString"


$dir = "C:\temp"
$latest = Get-ChildItem -Recurse -Filter filename*.txt -Path $dir | Sort-Object 
LastAccessTime -Descending | Select-Object -First 1 
$SEL = get-content $latest
if( $SEL -imatch "error" )
{
      Write-Host 'Errors found in the log file'
      #send email code to be added
}
else
{
      Write-Host 'No Errors'
}

I have tried this code and it works well at the moment. But wanted to make sure the code works even if there are two latest text files at the same given time.


Solution

  • File-system timestamps, at least as reported via .NET and therefore via PowerShell, use the System.DateTime data type, whose resolution is "one hundred nanoseconds or one ten-millionth of a second".

    I don't know if it's actually possible, but at the very least it seems highly unlikely that two or more files would end up with the exact same timestamp.

    If you don't want to take any chances, you can use the following approach:

    $dir = 'C:\temp'
    
    $latest = Get-ChildItem -Recurse -Filter filename*.txt -LiteralPath $dir |
                Group-Object LastWriteTime |
                  Select-Object -ExpandProperty Group -Last 1
    
    if ($latest | Select-String 'error') {
      Write-Verbose -Verbose 'Errors found in the log file'
      #send email code to be added
    }
    else {
      Write-Verbose -Verbose 'No Errors'
    }
    

    Note: