Question:
I keep getting error when I am trying to implement multiple line email body. I am suspecting bad syntax. Can’t find any example online. Any suggestions?
Error: Unexpected token 'EmployeeName"] to $AccountExpire"' in expression or statement.
1 2 3 4 5 6 7 8 9 10 11 |
$subject = "Email for $item["EmployeeName"]. Date expire $AccountExpire" $body=@" Name: $item["Employee"] Class: Contractor Depart: $item["Depart"] Region: $item["Region"] Manager: $item["Manager"] New Date: $NewDate "@ SendUpdateEmail($subject,$Body) |
Answer:
You need to escape those array index operations with a subexpression ($()
):
1 2 |
$subject = "Email for $($item["EmployeeName"]). Date expire $AccountExpire" |
Same goes for multi-line strings (or here-strings as they’re formally called):
1 2 3 4 5 6 |
$body=@" Name: $($item["Employee"]) Class: Contractor # and so on... "@ |
Personally, I’d go for a multi-line template and use the -f
format operator to fill in the values:
1 2 3 4 5 6 7 8 9 10 |
$bodyTemplate=@' Name: {0} Class: Contractor Depart: {1} Region: {2} Manager: {3} New Date: {4} '@ $body = $bodyTemplate -f $item["Employee"],$item["Depart"],$item["Region"],$item["Manager"],$NewDate |
When using -f
, you can also format different types of data, so if $NewDate
is a [DateTime]
object, you could control formatting for that inside the template, eg.:
1 2 3 4 |
@' Date: {0:HH:mm:ss} '@ -f (Get-Date) |
which would produce:
1 2 |
Date: 14:55:09 |
(assuming you did this a five to 3 in the afternoon)