我的服务器上部署了多个 Windows 服务。我想实现一个PowerShell脚本来实时监控这些服务的日志。它必须在日志文件中查找关键字(例如错误、异常),一旦出现任何错误,脚本就应向预先配置的电子邮件地址发送通知。 我在网络上进行了基本搜索,可以找到一些可以执行此操作的免费软件应用程序,但我不热衷于在服务器上安装这些应用程序。如果这可以通过基本的 PowerShell 脚本或批处理脚本来完成并且可以在后台运行,那就太好了。
我发现了 Get-Content 和 Type -wait 命令可以实时查看文件
Get-Content error.log -wait | where { $_ -match "ERROR" }
如果您可以添加一些可能有帮助的网络链接,我将非常感谢有关电子邮件通知部分的任何帮助。
有点复杂的是日志文件不会是恒定的,每天都会创建一个新的日志文件,脚本应根据文件名或创建日期等自动识别最新的文件。
File Name format is 8_05_2021.txt, 9_05_2021.txt, 10_05_2021.txt
最佳答案
如果我的逻辑是正确的,我认为这应该可行,这个脚本将无限期地运行。
据我所知,要在 PowerShell 中发送邮件,您有两种选择,一种是使用为此设计的 cmdlet:Send-MailMessage
但是,需要注意这一点:
Warning
TheSend-MailMessage
cmdlet is obsolete. This cmdlet does not guarantee secure connections to SMTP servers. While there is no immediate replacement available in PowerShell, we recommend you do not useSend-MailMessage
. For more information, see Platform Compatibility note DE0005.
您可以找到第二个选项here使用Net.Mail.MailMessage
。
现在对于脚本的代码,您可以使用以下内容:
# Define the full path of your logs folder
$logsFolder = 'fullPath\to\logsFolder'
# Function for monitoring and retrieving the newest log file Full Path
function Get-NewestLog ($LogPath) {
Get-ChildItem $LogPath -Filter *.txt | Sort-Object CreationTime -Descending |
Select-Object -First 1 -ExpandProperty FullName
}
# Get the newest log file
$logFilePath = Get-NewestLog -LogPath $logsFolder
while($true) {
# If we don't have today's date stored
# or the update trigger is True
if($updateDate -or -not $today) {
$today = [datetime]::Today
$updateDate = $false
}
if($today -lt [datetime]::Today) {
# Trigger our previous condition
$updateDate = $true
# Get the new log file for this day
$logFilePath = Get-NewestLog -LogPath $logsFolder
}
if((Get-Content $logFilePath -Raw) -match 'Error') {
# Send mail message goes here
}
Start-Sleep -Seconds 60
}
需要注意的是,如果日志文件中存在错误,这会每分钟向您的收件箱发送垃圾邮件,因此在此 block 中添加新条件可能是一个好主意:
if((Get-Content $logFilePath -Raw) -match 'Error') {
....
}
例如这样的事情:
if((Get-Content $logFilePath -Raw) -match 'Error' -and -not $emailSentThisDay) {
# Send mail message goes here
# Here you set this bool to True so you don't get spammed :D
$emailSentThisDay = $true
}
如果您会考虑这一点,那么您需要每天重置 $emailSentThisDay
bool 值,以便:
if($today -lt [datetime]::Today) {
# Trigger our previous condition
$updateDate = $true
# Reset the antispam bool if this is a new day
$emailSentThisDay = $false
# Get the new log file for this day
$logFilePath = Get-NewestLog -LogPath $logsFolder
}
关于windows - 实时监控Windows中日志文件中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67462276/