Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 34 ยท Language Basics

Strings, Quoting and Here-Strings

Master PowerShell strings: single vs double quotes, $() subexpressions, backtick escapes, here-strings, the -f format operator, and -join / -split with regex.

Text is everywhere in scripting: file names, log lines, messages, JSON, command arguments. PowerShell gives you two kinds of quotes with different meanings, a compact way to embed values in text, a block form for multi-line strings, and a handful of operators that cover most string work without a single method call.

Knowing which quote to use is the difference between a message that says Hello Ada and one that says Hello $name. This lesson covers single and double quotes, subexpressions with $( ), escapes, here-strings, the -f format operator, and -join and -split. It builds on Variables and Types and leads into Operators and Comparison.

Real PowerShell cannot run on this page, so the PowerShell snippets are read-only. The runnable examples use a JavaScript stand-in that emulates double-quoted expansion, the -f operator and -split / -join. It covers the documented basics, but real PowerShell parses much more, so the stand-in is a model and not the real parser.

Two kinds of quotes

'Single' Literal text. Nothing is expanded.
"Double" Variables and $( ) are expanded.

Choose single quotes unless you need expansion.

1 / 2

Single quotes and double quotes

Inside single quotes every character is literal. Inside double quotes, PowerShell replaces $name with the variable's value and processes backtick escapes.

POWERSHELL
$name = 'Ada'
'Hello $name'     # Hello $name
"Hello $name"     # Hello Ada

Use single quotes as your default, since they are safer and clearer, and reach for double quotes only when you want expansion. Paths with backslashes ('C:\Temp\new') are a good example: no escape processing means no surprises.

To put a quote character inside the same kind of quote, double it:

POWERSHELL
'It''s fine'        # It's fine
"She said ""hi"""   # She said "hi"
"It's fine"         # no problem: a single quote inside double quotes

Subexpressions

Expansion handles a plain variable name. For anything more, such as a property, a method call or arithmetic, wrap it in $( ):

POWERSHELL
$user = [pscustomobject]@{ Name = 'Ada'; Age = 36 }
"Name: $user.Name"            # Name: @{Name=Ada; Age=36}.Name    (a common surprise)
"Name: $($user.Name)"         # Name: Ada
"Next year: $($user.Age + 1)" # Next year: 37
"Files: $((Get-ChildItem).Count)"

The first line is the most common beginner bug: PowerShell expands only $user, turns that whole object into text, and leaves .Name as ordinary characters. Use $( ) whenever you want a property, an index like $($list[0]), or a command.

Another trap is a colon straight after a variable. "$name: hello" is read as a variable named name: in a scope or drive, which is an error or an empty result. Use "${name}: hello" or "$($name): hello". Braces (${name}) also separate the variable from letters that follow it: "${count}th".

An array in a string becomes its items joined by a space (the separator is the $OFS variable): "$(1,2,3)" gives 1 2 3.

Escape sequences

PowerShell's escape character is the backtick (`), not the backslash, only inside double quotes:

Sequence Means
`n and `r Newline, carriage return
`t Tab
`0 Null character
`" A double quote
`$ A literal dollar sign
`` A literal backtick
POWERSHELL
"Name`tAge`nAda`t36"       # two lines, tab-separated
"Price: `$5"                # Price: $5
'No `n escapes here'        # printed literally, because of the single quotes

Because backslash is not special, Windows paths stay readable. Remember that regular expressions (used by -match, -split and -replace) do use backslashes, see Regular Expressions and Text Processing.

A backtick at the very end of a line also continues the command onto the next line, but prefer splitting after a pipe, comma or opening brace, which needs no backtick.

Here-strings

A here-string holds multiple lines exactly as typed, with quotes allowed inside, which is perfect for JSON, SQL, HTML and long messages. It starts with @' or @" at the end of a line and ends with '@ or "@ at the start of a line:

POWERSHELL
$json = @'
{
  "name": "Ada",
  "tags": ["math", "code"]
}
'@

$name = 'Ada'
$mail = @"
Dear $name,

Your total is $($price * 2).
"@
  • @'...'@ is literal like single quotes: nothing is expanded.
  • @"..."@ expands variables and $( ) like double quotes.
  • The opening token must be the last thing on its line, and the closing token must be the first thing on its line, with no spaces before it. An indented closing token is a syntax error.
  • Quotes of either kind may appear freely inside.

The -f format operator

The -f operator fills numbered placeholders from a list on the right, and lets you format each value:

POWERSHELL
'{0} scored {1} points' -f 'Ada', 95
'{0:N2}' -f 1234.5          # 1,234.50
'{0:P0}' -f 0.256           # 26%
'{0:D5}' -f 42              # 00042
'{0:yyyy-MM-dd}' -f (Get-Date)
'{0,8}|{1,-8}|' -f 'right', 'left'    # width and alignment
'{{literal}} {0}' -f 5      # {literal} 5

picks the argument, {index:format} formats it, and {index,width} pads it (negative width pads on the right). Numeric and date formats follow the current culture, so N2 may use a comma as the decimal separator on some machines. Wrap a left-hand expression in parentheses when it is more complex, and when you pass several values use a comma-separated list, which becomes the array of arguments.

-join and -split

-join glues the items of a collection together. Its unary form joins with nothing:

POWERSHELL
'a', 'b', 'c' -join '-'      # a-b-c
-join ('a', 'b', 'c')        # abc
(Get-Process | Select-Object -First 3).Name -join ', '

-split cuts a string into an array. Its separator is a regular expression, not plain text, which trips up many people:

POWERSHELL
'a,b,c' -split ','           # a b c
'one  two   three' -split '\s+'
'a.b.c' -split '\.'          # a b c   (the dot must be escaped)
'a.b.c' -split '.'           # every character matches: only empty strings
'a.b.c' -split '.', 0, 'SimpleMatch'   # literal dot, no regex
'a,b,c,d' -split ',', 2      # a   and   b,c,d   (maximum 2 parts)

The unary -split cuts on whitespace: -split ' hello world ' gives hello and world. Both operators are case-insensitive by default, with -csplit as the case-sensitive form. Related: -replace is also regex based ('a.b' -replace '\.', '-'), while the .NET method .Replace('.', '-') is literal and case-sensitive.

String methods are available too: .Trim(), .ToUpper(), .Contains('x'), .StartsWith('ab'), .Substring(2, 3), .PadLeft(8). A string times a number repeats it ('ab' * 3 is ababab), and + joins two strings.

Stand-in: expanding a double-quoted string

This model of double-quoted expansion walks through a template. It understands $name, ${name}, $( ... ) (evaluated as a JavaScript expression with the variables in scope, so you write $price * 2) and the backtick escapes `n, `t, `$ and ``. The user object prints in PowerShell's @{Name=Ada; Age=36} form, so you can see the $user.Name trap.

JS How double quotes expand

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The line Name: $user.Name shows the property trap: only $user is expanded and .Name stays as plain text. The stand-in uses JavaScript expressions inside $( ), whereas real PowerShell evaluates PowerShell code there.

The next example models the -f operator (indexes, N2, P0, D5, widths) and the -split / -join pair, including the regex gotcha with a dot.

JS -f, -split and -join

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The splitter is only a model: PowerShell's -split also supports options such as SimpleMatch and a character-predicate form, and it treats capture groups slightly differently. The documented rule to remember is the one shown: the separator is a pattern.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. With $name = 'Ada', what does 'Hello $name' print?

    Single quotes are literal, so nothing is expanded. Double quotes would print Hello Ada.
  2. 2. What does "Name: $user.Name" do when $user is an object with a Name property?

    Expansion handles a plain variable name only. Use "$($user.Name)" for a property, a method call or any expression.
  3. 3. Which closing line is valid for a here-string that starts with @"?

    The closing token ("@ or '@) must be the first thing on its line. The opening token must be the last thing on its line.
  4. 4. What does 'a.b.c' -split '.' return?

    -split treats its separator as a regular expression. Escape the dot ('.') or use the SimpleMatch option for a literal split.
  5. 5. What does '{0:N2}' -f 1234.5 give on a machine with US English culture?

    N2 is a number format with a thousands separator and two decimals. The exact separators follow the current culture.

Summary

  • Single quotes are literal; double quotes expand $name and process backtick escapes, so prefer single quotes by default.
  • Use $( ) for properties, indexes, method calls and arithmetic in a string, and ${name} when a colon or letters follow a variable.
  • The escape character is the backtick (`n, `t, `$, `"), not the backslash.
  • Here-strings (@' '@ and @" "@) hold multi-line text, and the closing token must start its line.
  • -f fills , {1:N2}, {2,-10} placeholders and follows the current culture.
  • -join glues, -split cuts using a regular expression (escape the dot, or use SimpleMatch).

Next, compare and test values with Operators and Comparison.