简体   繁体   中英

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.

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:

  • The above uses the LastWriteTime rather than the LastAccessTime property, because presumably you're interested in when the files were last modified .

  • Group-Object implicitly outputs its object sorted by the grouping criterion.

  • Select-Object -ExpandProperty Group -Last 1 takes the last group, representing the file(s) with the latest modification timestamp, and outputs the file-system info comprising that group (via the .Group property of the objects output by Group-Object ).

  • Select-String accepts (multiple) file-system info objects via the pipeline and by default performs case-insensitive matching of the given regex against the files' contents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM