powershell - Extract content from log file from share location and send email in tabular format along with new headings to email
问题描述
I am trying to automate few of the daily health check tasks using PowerShell.
I would like to achieve the following (Step by Step), though I have a partial success in few,
Extract content of text (Log) file located at shared location (I have succeeded) by defining
$Path = Set-Location ...
etc.,Send email (succeeded) to mail box, by defining
Real help I need is here,
I want Headings to be appended in Email, along with original extracted text from Step 1,
For ex..
Original Text looks like this (extracted from text file at shared location):
01-01-2018 Number of Successful object - 1
I would like to add the header for this on email, like
date Description Number of Objects 01-01-2018 Successful objects 1
解决方案
假设在步骤 1 中收集的日志文件的内容是一个日志条目的字符串数组,其中每个字符串的格式类似于'01-01-2018 Number of Successful object - 1 '
在此示例中,我将该数组称为 $logEntries
# create an array to store the results objects in
$result = @()
# loop through this array of log entries
$logEntries | ForEach-Object {
# Here every text line is represented by the special variable $_
# From your question I gather they all have this format:
# '01-01-2018 Number of Successful object - 1 '
if ($_ -match '(?<date>\d{2}-\d{2}-\d{4})\s+(?<description>[^\-\d]+)[\s\-]+(?<number>\d+)\s*$') {
# Try to get the 'Succesful' or 'Failed' (??) text part out of the description
$description = ($matches['description'] -replace 'Number of|object[s]?', '').Trim() + ' object'
if ([int]$matches['number'] -ne 1) { $description += 's' }
# add to the result array
$result += New-Object -TypeName PSObject -Property ([ordered]@{
'Date' = $matches['date']
'Description' = $description
'Number of Objects' = $matches['number']
})
}
}
# now decide on the format of this result
# 1) as plain text in tabular form.
# This looks best when used with a MonoSpaced font like Courier or Consolas.
$result | Format-Table -AutoSize | Out-String
# or 2) as HTML table. You will have to style this table in your email.
# You may include a stylesheet using the '-CssUri' parameter, but inserting
# it in a nicely drawn-up HTML template will give you more creative freedom.
$result | ConvertTo-Html -As Table -Fragment
ps 因为 PSObject 有[ordered]
属性,这需要 PowerShell 版本 3.0 或更高版本。
推荐阅读
- python - 自定义腐蚀结果与 OpenCV 腐蚀不匹配
- javascript - Posting to MongoDB, What am I doing wrong?
- ios - UITableViewCell 中的 UITextView 键盘问题
- c++ - 在 CMakeLists.txt 中包含目录的更好方法
- django - Django project-apps:你对实现一个真正的数据库方案有什么看法?
- python - 从 Python 中的较大/多行字符串中计算包含 *both* 的两个字符串的行数
- c++ - 使用函数打开文件,然后让其他函数使用该文件?
- python - 如何修复 Conv1D 的输入形状?- 音频分类模型
- spring-data-jdbc - Spring Data JDBC不生成派生查询
- laravel - SQLSTATE[HY000]:一般错误:在 Laravel 中迁移期间出现 1005