$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.
File-system timestamps, at least as reported via .NET and therefore via PowerShell, use the
System.DateTimedata 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:
Note:
The above uses the
LastWriteTimerather than theLastAccessTimeproperty, because presumably you're interested in when the files were last modified.Group-Objectimplicitly outputs its object sorted by the grouping criterion.Select-Object -ExpandProperty Group -Last 1takes the last group, representing the file(s) with the latest modification timestamp, and outputs the file-system info comprising that group (via the.Groupproperty of the objects output byGroup-Object).Select-Stringaccepts (multiple) file-system info objects via the pipeline and by default performs case-insensitive matching of the given regex against the files' contents.