PowerShell provides the Start-Transcript and Stop-Transcript commandlets to record logging information in a log file.
Creating the log file
The simplest way to create a log file based on the current date is like this:
$now = Get-Date
$logfile = "c:\path\to\log\dir\file-" + $now.ToString("yyyy-MM-dd") + ".log"
Start-Transcript -path $logfile -force
Any output in the PowerShell console will now also be copied to the logfile.
To end logging, simply use
Stop-Transcript
Sending plain text email
After the log file has been closed, we parse it line-by-line, and append each line to a StringBuilder. Finally, the string contents of the StringBuilder is passed to an SmtpClient object to be sent:
$log = Get-Content $logfile
$body = New-Object System.Text.StringBuilder
foreach($line in $log)
{
[void] $body.AppendLine($line.ToString())
}
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body.ToString())
Sending HTML email
Depending on the email client you use, mails containing plain text log files need not necessarily be displayed with a fixed-width font. To force monospace fonts, we need to enclose the text inside a <pre> tag within HTML, and explicitly create an HTML message object:
$body = New-Object System.Text.StringBuilder
[void] $body.AppendLine("<pre>");
foreach($line in $log)
{
[void] $body.AppendLine($line.ToString())
}
[void] $body.AppendLine("</pre>");
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg = New-Object Net.Mail.MailMessage($emailFrom, $emailTo, $subject, $body.ToString())
$msg.IsBodyHTML = $true
$smtp.Send($msg)
Of course, the variables $emailFrom, $emailTo, $subject, and $smtpServer have to be defined according to your needs.