Link to home
Start Free TrialLog in
Avatar of samiam41
samiam41Flag for United States of America

asked on

Email log file after script completes - Powershell

Hey Experts.  I'd like to add the ability to email the log file once the script has finished running.  Below is the script I'd like to add the email functionality to:

$ServerList = @'
	"Name",			"Path"
	Servers
'@ | ConvertFrom-Csv
$LogFile = "\\w2k12FS01\PUBLIC\Tivoli_Master_Logs\Combined_{0}.log"

$Yesterday = (Get-Date).AddDays(-1)
$Pattern = (Get-Date).AddDays(-1).ToString('MM\/dd\/yyyy') + ' * --- SCHEDULEREC STATUS BEGIN*'
$Timestamp = $Yesterday.ToString('yyyyMMdd')
$in = $false
$ServerList | ForEach-Object {
	$Server = $_
	"========== $($Server.Name) ============================================================"
	Try {
		Switch -Wildcard (Get-Content -Path "\\$($Server.Name)\$($Server.Path.Replace(':', '$'))" -ErrorAction Stop) {
			$Pattern					{$in = $true}
			'*SCHEDULEREC STATUS END*'	{$in = $false}
			default						{If ($in) {$_}}
		}
	} Catch {
		"ERROR accessing '$($Server.Path)': $($_.Exception.Message)"
	}
} | Set-Content -Path $($LogFile -f $TimeStamp)

Open in new window


I tried adding this at the end of the script but it didn't work because of an error (Tivoli_Master_Logs\Combined_{0}.log value cannot be null).

$EmailFrom = "me"
$EmailTo = "me"
$EmailSubject = "Backup results for $($yesterday)"  
$SMTPServer = "smtp"

$emailattachment = $LogFile

$mailmessage = New-Object system.net.mail.mailmessage 
$mailmessage.from = ($emailfrom) 
$mailmessage.To.add($emailto)
$mailmessage.Subject = $emailsubject
$attachment = New-Object System.Net.Mail.Attachment($emailattachment, 'text/plain')
  $mailmessage.Attachments.Add($attachment)
$mailmessage.Body = ("<br />$('*'*72)<br />" + ((Get-Content -Path $LogFile) -join '<br />') + "<br />$('*'*72)<br />")

$mailmessage.IsBodyHTML = $true
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)  
#$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("$SMTPAuthUsername", "$SMTPAuthPassword") 
$SMTPClient.Send($mailmessage)

Open in new window


Thanks experts for your help!
SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of samiam41

ASKER

Here's what I get:

User generated image
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Script is really looking slick and very functional.  Thanks for your hard-work!