I'm generating a Slack message using a hashtable in Powershell.
Here is how the hashtable is generated:
$serviceitems = foreach ($r in $rows) {
@{
type = 'section'
text = @{
type = 'mrkdwn'
text = "*{0}*\n{1:C2}" -f $r[1], $r[0]
}
}
@{
type = 'divider'
}
}
The messsages show up in Slack but the \n
prints out instead of going to a new line like it should. The two *
make the text bold as intended. I tried adding a backtick to before \n
and also tried adding an extra \
. Both made no change.
CodePudding user response:
\
has no special meaning in PowerShell strings.
PowerShell uses `
(the so-called backtick) as the escape character, so you need escape sequence `n
inside an expandable (double-quoted) string ("..."
) in order to embed an actual newline (LF character) in the strings.
Simple example:
PS> "line 1`nline 2" | ForEach-Object { "[$_]" }
[line 1
line 2]
PowerShell happily accepts LF alone as a newline; if you do need CRLF newlines, use `r`n
. To refer to the platform-native newline sequence, use [Environment]::NewLine
($([Environment]::NewLine)
to use it inside "..."
).
See also:
- The conceptual about_Special_Characters help topic.
As for what you tried:
I tried adding a backtick to before
\n
and also tried adding an extra\
.
As implied at the top, \
should not be in the picture at all.
Trying `\n
results in `
escaping the \
character, which has no effect (escaping a non-special character is ignored); in other words: "`\n"
is the same as "\n"
which is verbatim \n