Home > Mobile >  powershell: newline in a single-quoted string?
powershell: newline in a single-quoted string?

Time:12-08

In powershell, double-quotes " indicate an "expandable" string, akin to "string interpolation" in other contexts. Single-quotes ' are strings which do not undergo interpolation.

I am a fan of this distinction, as it helps me anticipate how a particular string is being used.

however

Per these MS docs, Escape sequences are only interpreted when contained in double-quoted (") strings.

This seems to imply that I can't put a newline in a single-quoted string ?

CodePudding user response:

Indeed, PowerShell's verbatim strings ('...', i.e. single-quoted) support only one escape sequence: '', which allows you to embed a verbatim '

Therefore, your choices are:

  • Either: Embed a verbatim (actual) newline in your '...' string.

  • Or - and this applies to any character you want to generate programmatically rather than verbatim - use string concatenation ( ) or a templating approach via -f, the format operator

The following examples show these techniques:

'--- verbatim'
# Note: If the enclosing script uses Windows-style CRLF newlines,
#       so will this string ("`r`n").
'line1
line2'

'--- concatenation'
# Note: In lieu of "`n" you may use [char] 10
#       For Windows-style CRLF newlines, use "`r`n" or   [char] 13   [char] 10
'line1'   "`n"   'line2'

'--- -f operator:
'line1{0}line2' -f "`n"

If embedding verbatim newlines is an option, you may also use a verbatim here-string for better readability, which has the added advantage of not having to escape embedded ' characters:

# Here-string
@'
line1
line2
No escaping of ' needed.
'@

As with regular verbatim strings, it is the newline format of the enclosing script (Windows-style CRLF vs. Unix-style LF) that determines the format of the newlines used in the string.

  • Related