我正在尝试搜索多个使用不同文件名的日志文件。我想在每个日志中搜索一个主机名,找到匹配项后,将整个行复制到summary_ [date] .log并继续向其添加匹配行。所以我开始的是:
$captured = Get-ChildItem -recurse -Path \\nas1\share1 -Include *.log |
where { ($_.Name | Select-String -pattern ('PC1','PC2','PC3') -SimpleMatch) }
Now copy the line from each log file which contains the pattern and append it to a file with today's date stamp, so each week I'll have a file like \\nas1\share1\summary_03-07-2020.log
但这不是我想要的,因为它将捕获文件名并将它们附加到$ captured变量中。它还缺少将所有匹配行复制到带有时间戳的summary_ [date] .log的代码。
每个文本文件将包含以时间戳开头的其他行,如下所示:
03-07-2020_14-36-17-成功创建计算机[PC1]的备份。
因此,我要在共享中的几个文本文件中搜索几个主机名。如果文本文件包含主机名,则将包含主机名的行追加到summary_ [date] .log。最后,由于所有匹配行均以日期/时间戳开头,因此我需要将summary_ [date] .log文件的内容从最新日期到最旧日期进行排序。
从本质上讲,我应该每周以一个summary_ [date] .log结尾,该日志类似于以下内容:
03-07-2020_14-36-17 - Backup of computer [PC1] is successfully created.
03-07-2020_13-21-12 - Backup of computer [PC3] is successfully created.
03-07-2020_11-36-29 - Backup of computer [PC2] is successfully created.
这样,我就可以将当天的所有日志文件汇总到一个文件中,然后我将自动通过电子邮件将其发送到特定的电子邮件地址。
我该如何完成?
您当前的代码从文件名而不是内容中选择一个字符串。要执行您要执行的操作,可以使用以下类似方法:
$logFolder = '\\nas1\share1'
$outFile = Join-Path -Path $logFolder -ChildPath ('summary_{0:dd-MM-yyyy}.log' -f (Get-Date))
$captured = Get-ChildItem -Recurse -Path $logFolder -Include *.log | ForEach-Object {
($_ | Select-String -Pattern 'PC1','PC2','PC3' -SimpleMatch).Line
} | Sort-Object # sorting is optional of course
#output on screen
$captured
# output to new log file
$captured | Set-Content -Path $outFile
接下来,将该文件作为附件发送,如下所示:
# use splatting for cmdlets that take a lot of parameters
$params = @{
SmtpServer = 'yourmailserver'
From = '[email protected]'
To = '[email protected]'
Subject = 'Summary'
Body = 'Hi, in the attachment a summary of the backup logs'
Attachments = $outFile
# etc.
}
Send-Mailmessage @params
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句