从共享位置的日志文件中提取内容,并以表格格式将电子邮件以及新标题发送到电子邮件

时间:2018-08-17 03:33:49

标签: powershell powershell-v3.0

我正在尝试使用PowerShell自动执行一些日常运行状况检查任务。

我希望达到以下目标(逐步),尽管我在少数情况下取得了部分成功,

  1. 通过定义$Path = Set-Location ...等来提取位于共享位置(我已经成功)的文本(日志)文件的内容,

  2. 通过定义

  3. 将电子邮件(成功)发送到邮箱
  4. 我需要的真正帮助在这里

    我希望将标题以及从步骤1中提取的原始文本附加到电子邮件中

    例如。

    原始文本如下(从共享位置的文本文件中提取):

    01-01-2018 Number of Successful object - 1 
    

    我想在电子邮件上添加标题,例如

    date         Description          Number of Objects
    01-01-2018   Successful objects   1
    

1 个答案:

答案 0 :(得分:0)

假定步骤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

p.s。因为PSObject具有[ordered]属性,所以需要PowerShell 3.0或更高版本。