Email logs via Powershell functie

Email logs via Powershell functie

  • Comments 2
  • Likes

Vaak wil je in scripts bestanden zoals logfiles laten mailen. Dit gaat heel simpel met de volgende powershell functie:

Function _sendEmail($sender, $recipient, $subject, $body, $server, $filename){
Trap{
$script:sendEmailErrs += $error[0]
continue
}
$script:sendEmailErrs = @()
$msg = new-object System.Net.Mail.MailMessage $sender, $recipient, $subject, $body
If(Test-Path $filename){
$file = get-Item $filename
$attachment = new-object System.Net.Mail.Attachment $file
$msg.Attachments.Add($attachment)
}
ElseIf($filename -ne $null){
Throw{"File does not exist."}
}
$client = new-object System.Net.Mail.SmtpClient $server
$client.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$client.Send($msg)
$msg.Dispose()

return $sendEmailErrs
}

Je kan het aanroepen met:

_SendEmail "mark.priem@domein.com" "mark.priem@domein2.com" "hello world" "hello world" "smtp.fqdn.com" "c:\temp\logfile.log"

Zet het in je script of profile.

Comments
  • The only thing I would add is that you should dispose of the mailmessage object once you are down to prevent a filelock on the attachment file from causing problems.  When I worked with mailmessage class it seemed to lock the attachment as long as the powershell instance was running.

    basically add

      $msg.dispose()

    after

      $client.send($msg)

    Cheers

  • Thanks for the comment!

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
Search Blogs