Home > Back-end >  Format send email subject and body in powershell
Format send email subject and body in powershell

Time:06-18

I am working on changing Send-MailMessage formatting based on error or success. When there is an error, I would like to have the Subject and email Body text appear in red color. On success, I would like to change the Subject and email body text to Blue color. I was able to change the success email body to Blue color but the Subject and error email body does not work as expected.

error

PoSh Code:

$Emailsubject = "<p style=""color:red;"">Error occured</p><br><br>"
$ErrorMessage = "<p style=""color:red;"">" New-Object System.Exception ("Error: "   $error[0].Exception.InnerException.ToString())"</p><br><br>"

CodePudding user response:

You don't need to create a new object if you're just interested in interpolating the Inner Exception Message you can simply use the Subexpression operator $( ).

For example:

try {
    throw [System.Exception]::new('', 'some inner exception')
}
catch {
    $ErrorMessage = "<p style=""color:red;"">Error: $($error[0].Exception.InnerException.Message)</p><br><br>"
}

$ErrorMessage would become the following in HTML:

<p style="color:red;">Error: some inner exception</p><br><br>

As aside, using the .ToString() Method is definitely not recommended in this case, if the error you're catching does not have an Inner Exception, you would get a new error.

For Example:

try {
    throw [System.Exception]::new('does not have inner exception')
}
catch {
    $ErrorMessage = "<p style=""color:red;"">Error: $($error[0].Exception.InnerException.ToString())</p><br><br>"
}

Would result in the following Error:

You cannot call a method on a null-valued expression.

  • Related