pbj
pbj

Reputation: 719

Format send email subject and body in powershell

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>"

Upvotes: 2

Views: 684

Answers (1)

Santiago Squarzon
Santiago Squarzon

Reputation: 61103

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.

Upvotes: 1

Related Questions