寻找一个Powershell脚本,该脚本在目录中获取最新的txt文件并搜索关键字“ 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'
}

我已经尝试过此代码,目前效果很好。但是,即使在给定的时间同时有两个最新的文本文件,也要确保代码能够正常工作。

解决方法

文件系统时间戳(至少是通过.NET并因此通过PowerShell报告的),使用System.DateTime数据类型,其分辨率为“一百纳秒或十分之一” -百万分之一秒”。

我不知道是否真的可能,但是至少看起来可能性很小两个或多个文件的确切名称相同的时间戳。

如果您不想冒险,可以使用以下方法:

$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'
}

注意:

  • 上面使用LastWriteTime而不是LastAccessTime属性,因为大概您对文件的最后修改时间感兴趣。

  • Group-Object隐式输出按分组标准排序的对象。

  • Select-Object -ExpandProperty Group -Last 1接受最后一个组,代表具有 latest 修改时间戳的文件,并输出包含该组的文件系统信息(通过{{ .Group输出的对象的1}}属性。

  • Select-String通过管道接受(多个)文件系统信息对象,默认情况下,将给定的正则表达式与文件内容进行不区分大小写的匹配。