PowerShell导出Eventvwr事件日志发邮件时如何截断Message字段
实现Message字段截断的修改方案
要实现Message字段截断避免邮件内容过长,只需要在字段选择阶段通过PowerShell计算属性对Message做长度限制即可,修改逻辑如下:
核心修改点
将原有代码中选择字段的行:
$out = $el_sorted|Select MachineName, EntryType, TimeGenerated, Source, EventID, Message #| Export-CSV $ExportFile -NoTypeInfo #EXPORT
替换为以下内容,可自行调整数值修改截断长度:
$out = $el_sorted | Select-Object MachineName, EntryType, TimeGenerated, Source, EventID, @{ Name = 'Message'; Expression = { # 保留前200个字符,超出部分补...,可按需修改长度 if ($_.Message.Length -gt 200) { $_.Message.Substring(0,200) + '...' } else { $_.Message } } } #| Export-CSV $ExportFile -NoTypeInfo #需要导出CSV则取消该行前的注释
修改后的完整脚本
# # 本脚本用于导出整合、筛选后的事件日志到CSV,并发送通知邮件 # # 邮箱配置 $FromAddress = 'abc.com' $ToAddress = '123.com' $SmtpServer = 'xyz.com' Set-Variable -Name EventAgeDays -Value 4 # 取最近X天的事件,这里配置的是4天 Set-Variable -Name CompArr -Value @("abcedf.com") # 替换为你的服务器名称列表 Set-Variable -Name LogNames -Value @("Application") # 检查的日志类型 Set-Variable -Name EventTypes -Value @("Information") # 要筛选的事件级别 Set-Variable -Name ExportFolder -Value "C:\xxx\" Set-Variable -Name Source -Value @("123", "111") $el_c = @() # 整合后的事件日志集合 $now=get-date $startdate=$now.adddays(-$EventAgeDays) $ExportFile=$ExportFolder + "Out" + $now.ToString("yyyy-MM-dd---hh-mm-ss") + ".csv" # 导出文件名,不能用冒号等特殊字符 foreach($comp in $CompArr) { foreach($log in $LogNames) { foreach ($src in $Source) { Write-Host Processing $comp\$log $el = get-eventlog -ComputerName $comp -log $log -After $startdate -EntryType $EventTypes -Source $src -Newest 1 -InstanceId 30000 $el_c += $el # 整合事件 } } } $el_sorted = $el_c | Sort-Object TimeGenerated # 按事件生成时间排序 Write-Host Exporting to $ExportFile # 字段选择+Message截断逻辑 $out = $el_sorted | Select-Object MachineName, EntryType, TimeGenerated, Source, EventID, @{ Name = 'Message'; Expression = { # 保留前200个字符,超出部分补...,可按需修改长度 if ($_.Message.Length -gt 200) { $_.Message.Substring(0,200) + '...' } else { $_.Message } } } #| Export-CSV $ExportFile -NoTypeInfo #需要导出CSV则取消该行前的注释 Write-Host Done! $msgBody = $out Send-MailMessage -from $FromAddress -to $ToAddress -SmtpServer $SmtpServer -Subject "TL Stage Ingester Status from $CompArr $startdate" -Body ( $msgBody | Out-String)
注意事项
- 可根据实际需求调整截断长度,将
Substring(0,200)中的200修改为你想要的字符数即可 - 原代码中存在误注释的循环闭合符号,已在完整脚本中修正,避免出现语法错误
内容的提问来源于stack exchange,提问作者nikon D3400
相关产品推荐
相关产品推荐

