首页 > 解决方案 > 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,

  1. Extract content of text (Log) file located at shared location (I have succeeded) by defining $Path = Set-Location ... etc.,

  2. Send email (succeeded) to mail box, by defining

  3. 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
    

标签: powershellpowershell-3.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

ps 因为 PSObject 有[ordered]属性,这需要 PowerShell 版本 3.0 或更高版本。


推荐阅读