您可以为此使用 Jobs。在某个后台作业中读取文件,并让“前台”脚本等到天变了。一旦一天改变了,终止旧工作并开始一个新的工作来查看新文件。
while($true)
{
$now = Get-Date
$fileName = 'System_{0}{1}{2}.log' -f $now.Year, $now.Month, $now.Day
$fullPath = "some directory\$fileName"
Write-Host "[$(Get-Date)] Starting job for file $fullPath"
$latest = Start-Job -Arg $fullPath -ScriptBlock {
param($file)
# wait until the file exists, just in case
while(-not (Test-Path $file)){ sleep -sec 10 }
Get-Content $file -wait | where {$_ -match "some regex"} |
foreach { send_email($_) }
}
# wait until day changes, or whatever would cause new log file to be created
while($now.Date -eq (Get-Date).Date){ sleep -Sec 10 }
# kill the job and start over
Write-Host "[$(Get-Date)] Stopping job for file $fullPath"
$latest | Stop-Job
}