Monday, January 5, 2015

Powershell - Send-MailMessage carriage returns in Body

With my learning Powershell one of the tasks I worked on I wanted the output emailed and carriage returns between each output.  Turns out I didn't need to do the carriage returns (Select-String post), but I realized this after figuring out how HA!

I know I'll need this for a later project, so I'm posting it for when my memory needs jogged.

The following takes some form of data (in this case ADUser names) and then adds a carriage return between each object so that your email looks nice and pretty (and readable).

Note: testing was done with Powershell v4.0
$emailTo = "myemail@mydomain.com"
$emailFrom = "alarmalarm@mydomain.com"
$smtpServer = "address"
$smtpSubject = "Error detected in logs"
$smtpBody = ""

#smtp function
Function smtpSend {
    Send-MailMessage -From $emailFrom -To $emailTo -Subject $smtpSubject -Body $smtpBody -SmtpServer $smtpServer
    }

#populate array with list of users
$users = Get-ADUser -filter "SamAccountName -like 'j*'"

#add carriage return between each object in array
foreach ($user in $users) {$smtpBody = $smtpBody + $user.name + "`r`n"}

#call smtpSend Function
smtpSend

No comments:

Post a Comment