Strings
Prerequisites: Data types
Double vs single quotes
$name = 'Ada'
"Hello, $name!"
'Hello, $name!'
"Next year you'll be $(36 + 1)."
"Name length: $($name.Length)"
"Tab:`tafter tab"
Hello, Ada!
Hello, $name!
Next year you'll be 37.
Name length: 3
Tab: after tab
- Double quotes expand variables and
$( ... )subexpressions. - Single quotes keep everything literally.
- Inside double quotes, use
$( )for anything more than a plain variable — property access like$user.Nameneeds"$($user.Name)". - The escape character is the backtick (
`):`ttab,`nnewline,`$a literal dollar sign.
The format operator: -f
'{0} costs {1:N2}' -f 'Monitor', 249.99
'{0,-10}|{1,6:N1}' -f 'Keyboard', 89
'{0:D3}' -f 7
'{0:P0}' -f 0.256
Monitor costs 249.99
Keyboard | 89.0
007
26%
-f fills numbered placeholders: {0} is the first value. After a colon,
a format — N2 (number, 2 decimals), D3 (3 digits), P0
(percentage). After a comma, a width (negative means left-aligned).
C formats currency using the computer's regional settings.
String methods and operators
$text = ' Hello, PowerShell World '
$text.Trim()
$text.Trim().ToUpper()
$text.Trim().Replace('World', 'Friends')
$text.Trim().Split(', ')
'a,b,c' -split ','
'x', 'y', 'z' -join '-'
$text.Contains('Shell')
$text.Trim().StartsWith('Hello')
Hello, PowerShell World
HELLO, POWERSHELL WORLD
Hello, PowerShell Friends
Hello
PowerShell World
a
b
c
x-y-z
True
True
-split and -join are PowerShell operators; -split uses a regular
expression.
Here-strings
A here-string spans several lines. The opening @" and closing "@
must be on their own lines:
$name = 'Ada'
$message = @"
Dear $name,
Thanks for signing up.
"@
$message
Dear Ada,
Thanks for signing up.
@' ... '@ is the literal (non-expanding) version.
Common mistakes
"Total: $order.Total"prints the whole object followed by.Total. Write"Total: $($order.Total)".- Using a backslash as an escape character — in PowerShell,
\nis just a backslash and ann.