Share via


Email logs via Powershell functie

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, $bodyIf(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

  • Anonymous
    January 01, 2003
    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

  • Anonymous
    January 01, 2003
    Thanks for the comment!