String Formatting, Split, Join, Replace, and Other Operators
The PowerShell operators for building and taking apart text (-f, -split, -join, -replace) plus ternary, null-coalescing, chaining, call, splatting and redirection.
By The Dark DebuggerUpdated 30 min read
This article picks up where Comparison, Logical, and Arithmetic Operators
left off. It covers the operators that build and take apart text (-f, -split, -join,
-replace), the range operator, the PowerShell 7 conveniences (?:, ??, ?., &&,
||), and the operators that run things and move output around: &, dot-sourcing,
splatting and redirection. You should be comfortable with
variables and the
pipeline first.
Several operators here exist only in PowerShell 7. Each one is marked, along with what Windows PowerShell 5.1 says when you try it.
Why these operators matter
Most automation ends up turning one text format into another. A backup tool writes
2026-11-08T23:45:02Z|files01|incremental|734003200|FAILED|45, and someone wants a
readable morning report. A deploy script gets DATABASE_URL=postgres://... from an
environment file and needs the part after the first =. A log needs email addresses
masked before it is attached to a ticket.
You can do all of that with loops and substring arithmetic, but PowerShell gives you an operator for each job, and a script built from them is shorter and easier to check. The Where you'll use this section builds that backup report from the pieces below.
The format operator -f
-f takes a template string on the left and values on the right. Each {N} placeholder
is replaced by the value at index N:
'{0} has {1} pending updates' -f 'web01', 12
'{1} before {0}, then {1} again' -f 'first', 'second'web01 has 12 pending updates
second before first, then second againA placeholder has three parts, {index,alignment:format}, and the last two are optional.
The alignment pads the value to a width: positive numbers right-align, negative numbers
left-align. That is how you print columns that line up:
'[{0,-12}][{1,6}]' -f 'web01', 42
'[{0,12}][{1,-6}]' -f 'web01', 42[web01 ][ 42]
[ web01][42 ]Number formats
The format part takes standard .NET format strings:
'{0:N0}' -f 1234567
'{0:N2}' -f 1234.5678
'{0:F1}' -f 3.14159
'{0:P1}' -f 0.8734
'{0:D5}' -f 42
'{0:X}' -f 255
'{0:x8}' -f 255
'{0:0.00}' -f 2.5
'{0:#,##0.0} MB' -f 15234.561,234,567
1,234.57
3.1
87.3 %
00042
FF
000000ff
2.50
15,234.6 MB| Format | Meaning | Typical use |
|---|---|---|
N0, N2 | Number with thousands separators, N decimals | byte counts, request totals |
F1 | Fixed-point, no separators | durations, percentages you append % to yourself |
P1 | Multiply by 100 and add a percent sign | ratios such as 0.8734 |
D5 | Integer padded with zeros to 5 digits | build numbers, sequence IDs |
X, x8 | Hexadecimal, upper or lower case, optional width | error codes, flags |
0.00, #,##0.0 | Custom pattern: 0 always prints, # only if needed | anything the standard ones do not cover |
The output follows the current culture. My lab ran with the invariant culture, which is
why P1 printed 87.3 % with a space; Windows PowerShell 5.1 on an en-US machine prints
87.3%, and a German culture would print 1.234,57 for N2. If a file is read by other
programs, format numbers deliberately rather than relying on whatever culture the server has.
Date and time formats
Dates take custom format strings. Note that MM is month and mm is minutes:
$d = Get-Date '2026-11-09 14:05:09'
'{0:yyyy-MM-dd HH:mm:ss}' -f $d
'{0:yyyyMMdd-HHmm}' -f $d
'{0:ddd dd MMM yyyy}' -f $d
'{0:o}' -f $d
'{0:hh\:mm\:ss}' -f [timespan]::FromSeconds(3725)2026-11-09 14:05:09
20261109-1405
Mon 09 Nov 2026
2026-11-09T14:05:09.0000000
01:02:05yyyyMMdd-HHmm is the format I use for file names, because it sorts correctly as text. o
is ISO 8601, the safe choice for logs and APIs. A TimeSpan needs its colons escaped with a
backslash.
Literal braces
To print a { or }, double it. That matters when the template is JSON:
'{{ "service": "{0}", "replicas": {1} }}' -f 'billing', 3{ "service": "billing", "replicas": 3 }A small aligned report
Alignment and number formats together give you a readable table without Format-Table:
$disks = @(
[pscustomobject]@{ Mount = '/'; SizeGB = 250; UsedGB = 201.4 }
[pscustomobject]@{ Mount = '/var/lib/postgresql'; SizeGB = 1024; UsedGB = 512.9 }
[pscustomobject]@{ Mount = '/boot'; SizeGB = 1; UsedGB = 0.31 }
)
'{0,-22} {1,8} {2,8} {3,6}' -f 'Mount', 'Size GB', 'Used GB', 'Use%'
foreach ($d in $disks) {
'{0,-22} {1,8:N0} {2,8:N1} {3,6:P0}' -f $d.Mount, $d.SizeGB, $d.UsedGB, ($d.UsedGB / $d.SizeGB)
}Mount Size GB Used GB Use%
/ 250 201.4 81 %
/var/lib/postgresql 1,024 512.9 50 %
/boot 1 0.3 31 %Unlike Format-Table, this produces plain strings, so you can write them to a file, put
them in an email body or a chat message, and they will look the same everywhere.
Arrays on the right-hand side
The right side of -f is an array of arguments. If you pass a variable that holds an
array, its elements become the arguments:
$parts = 'web01', 'eu-west-1'
'{0} in {1}' -f $parts
'Servers: {0}' -f $parts
'Servers: {0}' -f ($parts -join ', ')web01 in eu-west-1
Servers: web01
Servers: web01, eu-west-1The second line silently dropped eu-west-1. When you want a whole list in one placeholder,
join it first.
String interpolation or -f?
Double-quoted strings expand variables, and $( ) evaluates any expression inside a string:
$server = 'web01'; $free = 7.20000000018626
"Server $server has $free GB free"
"Server $server has $([math]::Round($free, 1)) GB free"
'Server {0} has {1:N1} GB free' -f $server, $freeServer web01 has 7.20000000018626 GB free
Server web01 has 7.2 GB free
Server web01 has 7.2 GB freeInterpolation only expands the variable name. A property access needs $( ), or you get the
whole object's text followed by a literal .Name:
$svc = [pscustomobject]@{ Name = 'nginx'; Status = 'Running' }
"Service: $svc.Name is $svc.Status"
"Service: $($svc.Name) is $($svc.Status)"Service: @{Name=nginx; Status=Running}.Name is @{Name=nginx; Status=Running}.Status
Service: nginx is RunningA colon right after a variable name is read as a scope or drive prefix ($env:PATH,
$script:count), so a host:port string fails to parse:
$server = 'web01'; $port = 8443
"Connecting to $server:$port"ParserError:
Line |
1 | "Connecting to $server:$port"
| ~~~~~~~~
| Variable reference is not valid. ':' was not followed by a valid
| variable name character. Consider using ${} to delimit the name.Braces delimit the name, as the message suggests:
$server = 'web01'; $port = 8443
"Connecting to ${server}:$port"Connecting to web01:8443My rule of thumb: use interpolation for short messages with plain variables, and -f when
you need number or date formatting, alignment, or more than two $( ) blocks.
Splitting text with -split
-split breaks a string into an array of substrings:
'web01,web02,db01' -split ','web01
web02
db01The delimiter is a regular expression
This is the gotcha that catches everyone once. A dot in a regex means "any character", so
splitting an IP address on '.' splits on every character:
'10.0.4.17' -split '.'
('10.0.4.17' -split '.').Count
10Ten empty strings. Escape the dot, or tell -split to treat the delimiter literally with
the SimpleMatch option (the 0 before it means "no limit on the number of pieces"):
'10.0.4.17' -split '\.'
'10.0.4.17' -split '.', 0, 'SimpleMatch'10
0
4
17
10
0
4
17The characters that need escaping in a regex delimiter are . $ ^ { [ ( | ) * + ? \. Pipes
are the common one in log formats: split on '\|', not '|'.
Unary -split splits on whitespace
With nothing on the left, -split splits on runs of whitespace and drops leading and
trailing space. That is exactly what you want for columnar command output:
-split ' nginx running 2.3% '
(' nginx running 2.3% ' -split ' ').Countnginx
running
2.3%
11Splitting the same line on a single space gives 11 pieces, most of them empty.
Limiting the number of pieces
A second operand caps the number of substrings. This is the right way to split
key=value lines where the value may contain the delimiter:
$name, $value = 'DATABASE_URL=postgres://app@db01:5432/orders?sslmode=require' -split '=', 2
$name
$valueDATABASE_URL
postgres://app@db01:5432/orders?sslmode=requireWithout the 2, the sslmode=require part would have been split off too. Multiple
assignment (from the previous article)
puts each piece in its own variable.
Empty fields, captured delimiters and script blocks
Consecutive delimiters produce empty strings. Filter them with -ne '', which works because
a comparison on a collection filters it:
'eu-west-1,,us-east-1,' -split ','
('eu-west-1,,us-east-1,' -split ',') -ne ''eu-west-1
us-east-1
eu-west-1
us-east-1If the delimiter pattern contains a capture group, the delimiters are kept in the output, which is useful for tokenising:
'10+4-3' -split '[+-]'
'10+4-3' -split '([+-])'10
4
3
10
+
4
-
3The delimiter can also be a script block. It runs once per character, with the character in
$_, and the string is split wherever it returns $true:
'eu-west-1;eu-central-1,us-east-1' -split { $_ -eq ';' -or $_ -eq ',' }eu-west-1
eu-central-1
us-east-1A character class (-split '[;,]') does the same thing here and is faster; keep the script
block for rules a regex cannot express. Like the comparison operators, -split ignores case,
and -csplit is the case-sensitive version.
-split versus the .Split() method
Strings also have a .Split() method, and its behaviour depends on your PowerShell version:
'a--b-c'.Split('--')
'a--b-c' -split '--'a
b-c
a
b-cThat is PowerShell 7, where .NET has a Split(string) overload. Windows PowerShell 5.1 runs
on .NET Framework, which converts '--' to an array of characters and splits on every -,
returning a, an empty string, b and c. Prefer the -split operator in scripts that
must run on both.
Joining with -join
-join is the inverse of -split. With a separator on the right it joins with that
separator; as a unary operator it joins with nothing:
$servers = 'web01', 'web02', 'db01'
$servers -join ', '
-join $servers
1..5 -join '+'web01, web02, db01
web01web02db01
1+2+3+4+5Unary -join binds more tightly than the comma, so a list written inline needs parentheses:
-join 'web', '01'
-join ('web', '01')web
01
web01-join converts each element with its ToString() method. For a custom object that is an
empty string, so join the property you want instead:
$services = [pscustomobject]@{ Name = 'nginx' }, [pscustomobject]@{ Name = 'redis' }
$services -join ', '
$services.Name -join ', ',
nginx, redisReplacing text with -replace
-replace takes a regex pattern and a replacement and replaces every match. Like the
other operators it ignores case unless you use -creplace:
'Connection timed out after 30 s' -replace 'timed out', 'TIMEOUT'
'ERROR error Error' -replace 'error', 'E'
'ERROR error Error' -creplace 'error', 'E'Connection TIMEOUT after 30 s
E E E
ERROR E ErrorBecause the pattern is a regex, one line can mask every email address or IP in a log before you paste it into a ticket, or strip everything that is not a digit:
'2026-11-09 14:02:17 user=alice@example.com action=login' -replace '\S+@\S+', '[redacted]'
'192.168.10.24 - GET /health 200' -replace '\b\d{1,3}(\.\d{1,3}){3}\b', 'x.x.x.x'
'build #4812 (main)' -replace '\D', ''2026-11-09 14:02:17 [redacted] action=login
x.x.x.x - GET /health 200
4812Leave out the replacement (or pass '') to delete what matched.
Capture groups: $1, ${name} and the double-quote trap
Parentheses in the pattern capture text, and the replacement refers to the captures as
$1, $2, or ${name} for named groups. Reordering a date is the classic example:
'2026-11-09' -replace '(\d{4})-(\d{2})-(\d{2})', '$3/$2/$1'
'Smith, Jane' -replace '(?<last>\w+), (?<first>\w+)', '${first} ${last}'09/11/2026
Jane SmithNow the same replacement in double quotes:
'2026-11-09' -replace '(\d{4})-(\d{2})-(\d{2})', "$3/$2/$1"//PowerShell expanded $3, $2 and $1 as PowerShell variables before the regex engine
saw them. They do not exist, so they became empty strings. Use single quotes for
replacement strings. If you also need a PowerShell variable in the replacement, use double
quotes and escape the regex references with a backtick:
$sep = '.'
'2026-11-09' -replace '(\d{4})-(\d{2})-(\d{2})', "`$3$sep`$2$sep`$1"09.11.2026Special characters on both sides
The pattern is a regex, so escape literal dots and other metacharacters, or let
[regex]::Escape() do it. In the replacement, $ is special, and $$ produces a literal
dollar sign:
'v1.5.2' -replace '.', '-'
'v1.5.2' -replace '\.', '-'
'v1.5.2' -replace [regex]::Escape('.'), '-'
'Price: 5 EUR' -replace '(\d+) EUR', '$$$1'------
v1-5-2
v1-5-2
Price: $5Script block replacements (PowerShell 7)
In PowerShell 6.1 and later, the replacement can be a script block. It receives each match
as $_ (a Match object) and returns the replacement text, so you can compute it:
'cpu=0.42 mem=0.71' -replace '\d\.\d+', { '{0:P0}' -f [double]$_.Value }cpu=42 % mem=71 %Windows PowerShell 5.1 does not support this; there you would call
[regex]::Replace() with a script block cast to a MatchEvaluator.
Chaining and collections
-replace operations chain left to right, and on a collection they apply to every element:
' Web01.PROD.Internal '.Trim() -replace '\.internal$', '' -replace '\.', '-'
$files = 'app.log', 'app.log.1', 'error.log'
$files -replace '\.log', '.txt'Web01-PROD
app.txt
app.txt.1
error.txt.Replace() versus -replace
The string method .Replace() does a literal, case-sensitive replacement. No regex, so no
escaping:
'C:\Logs\app.log'.Replace('\', '/')
'C:\Logs\app.log' -replace '\\', '/'
'Error ERROR error'.Replace('error', 'E')
'Error ERROR error'.Replace('error', 'E', 'OrdinalIgnoreCase')C:/Logs/app.log
C:/Logs/app.log
Error ERROR E
E E E-replace | .Replace() | |
|---|---|---|
| Pattern | Regular expression | Literal text |
| Case | Insensitive (-creplace for sensitive) | Sensitive by default |
| Capture groups | Yes | No |
| Works on arrays | Yes, every element | No, strings only |
| Version notes | Script block replacement needs PowerShell 6.1+ | The case-insensitive overload needs PowerShell 7; 5.1 says Cannot find an overload for "Replace" and the argument count: "3". |
Use .Replace() when the text to find comes from a variable and may contain regex
characters (file paths, URLs, user input). Use -replace for everything pattern-shaped.
The range operator ..
.. produces every integer between two endpoints, counting up or down:
1..5
5..1
-2..21
2
3
4
5
5
4
3
2
1
-2
-1
0
1
2Combined with -f, it generates names; combined with indexing, it slices arrays (negative
indexes count from the end):
1..3 | ForEach-Object { 'web{0:D2}' -f $_ }
$lines = 'line1', 'line2', 'line3', 'line4', 'line5', 'line6'
$lines[0..2]
$lines[-2..-1]web01
web02
web03
line1
line2
line3
line5
line6In PowerShell 7 the endpoints can also be characters, so 'a'..'e' returns a to e.
In Windows PowerShell 5.1 the same line fails with Cannot convert value "a" to type "System.Int32"; use [char[]](97..101) there. Slicing has a trap with negative ranges,
covered in Arrays, Hashtables, and Custom Objects.
The ternary operator ?: (PowerShell 7)
condition ? valueIfTrue : valueIfFalse picks one of two values:
$freeGB = 7.2
$status = $freeGB -lt 10 ? 'LOW' : 'OK'
$status
"Disk is $($freeGB -lt 10 ? 'low' : 'fine')"LOW
Disk is lowThe spaces around ? are not optional. ? is a legal character in a variable name, so
without a space PowerShell reads $ok? as a variable called ok?:
$ok = $true
$ok?'yes':'no'ParserError:
Line |
1 | $ok?'yes':'no'
| ~~~~~
| Unexpected token ''yes'' in expression or statement.With spaces ($ok ? 'yes' : 'no') it returns yes. Ternaries can be chained, but past two
outcomes a switch reads better (see Conditionals):
$code = 503
$code -lt 300 ? 'ok' : $code -lt 500 ? 'client error' : 'server error'server errorNull-coalescing ?? and ??= (PowerShell 7)
$a ?? $b returns $a unless it is $null, in which case it returns $b. It is the
cleanest way to give environment variables and optional settings a default:
$env:LOG_LEVEL = $null
$logLevel = $env:LOG_LEVEL ?? 'Information'
$logLevel
$retries = 0
$retries ?? 3
'' ?? 'default'
$null ?? 'default'Information
0
defaultOnly $null triggers the default. 0 and the empty string are values, so they pass
through (the empty line in the output is the empty string). That is usually what you want:
MAX_RETRIES=0 should mean zero retries, not "use the default".
??= assigns only when the variable is $null. It is handy for caching an expensive value
the first time it is needed:
$cache = $null
$cache ??= Get-Date '2026-11-09'
$cache ??= Get-Date '2030-01-01'
$cache.Year2026If you are used to $name || 'anonymous' from JavaScript or Bash, note that -or returns a
boolean, not a value. The ternary handles "empty or null":
$name = ''
$name -or 'anonymous'
$name ? $name : 'anonymous'True
anonymousNull-conditional member access ?. and ?[] (PowerShell 7.1+)
?. accesses a member only if the object is not $null; ?[] does the same for indexing.
The variable name must be wrapped in braces, for the same reason as the ternary:
$response = $null
${response}?.StatusCode
$response.StatusCode
$response = [pscustomobject]@{ StatusCode = 200; Tags = 'canary', 'eu' }
${response}?.StatusCode
${response}?.Tags?[0]200
canaryNotice that $response.StatusCode on a $null variable did not fail either. Outside
strict mode, reading a property of $null just returns $null. Where ?. earns its place
is method calls, which do fail:
$response = $null
$response.ToString()InvalidOperation: You cannot call a method on a null-valued expression.${response}?.ToString() returns nothing instead of failing. Forgetting the braces is a
silent bug: $response?.StatusCode reads a variable named response?, which does not
exist, so you get $null even when $response is set. With Set-StrictMode -Version Latest
you at least get told:
$response = [pscustomobject]@{ StatusCode = 200 }
$response?.StatusCode
Set-StrictMode -Version Latest
$response?.StatusCodeInvalidOperation: The variable '$response?' cannot be retrieved because it has not been set.The first $response?.StatusCode printed nothing even though the status code is 200.
What Windows PowerShell 5.1 says
None of ?:, ??, ??=, ?., && or || exist in 5.1, and a script that uses them
fails to parse before any of it runs. In 5.1, $ok ? 'yes' : 'no' gives
Unexpected token '?' in expression or statement., $x ?? 1 gives
Unexpected token '??' in expression or statement., and echo a && echo b gives
The token '&&' is not a valid statement separator in this version. If a script must
run on both, use if/else instead, or add #Requires -Version 7 at the top so the
failure is explicit.
Pipeline chain operators && and || (PowerShell 7)
a && b runs b only if a succeeded; a || b runs b only if a failed. For native
programs, success means exit code 0, which PowerShell stores in $LASTEXITCODE:
grep -q ERROR ./logs/app.log && 'errors found' || 'no errors'
$LASTEXITCODE
grep -q INFO ./logs/app.log && 'info lines found'
$LASTEXITCODEno errors
1
info lines found
0grep exits with 1 when nothing matches, so the || branch ran. A build-and-package step
reads the same way it would in Bash:
tar -czf site.tgz ./site && 'packaged' || 'packaging failed'
tar -czf missing.tgz ./missing && 'packaged' || 'packaging failed'packaged
/usr/bin/tar: ./missing: Cannot stat: No such file or directory
/usr/bin/tar: Exiting with failure status due to previous errors
packaging failedFor cmdlets, success means $? is $true, that is, the command wrote no error. That is
not the same as returning $true:
Test-Path /nope && 'found it'False
found itTest-Path ran successfully and output False, so && carried on. Use if (Test-Path ...)
when you care about the value. A cmdlet that writes an error does trigger ||:
Get-Item /nope && 'found it' || 'not found'Get-Item: Cannot find path '/nope' because it does not exist.
not foundThe call operator &
& runs a command whose name or path is in a string, or a script block:
$tool = 'uname'
& $tool -s
$check = { param($name) "checking $name" }
& $check 'db01'Linux
checking db01You need it whenever a path is quoted, which is any path with spaces. Without &, a quoted
path is just a string, and without quotes the space splits the path:
'./tools dir/report tool.ps1'
& './tools dir/report tool.ps1' -Name db01./tools dir/report tool.ps1
Generating report for db01./tools dir/report tool.ps1./tools: The term './tools' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.& runs the target in a child scope: variables and functions it defines disappear when
it finishes. Running native programs with & (exit codes, argument quoting) is covered in
Providers, Drives, Aliases, and Native Commands.
Dot-sourcing .
Dot-sourcing runs a script in the current scope, so whatever it defines stays defined.
It is how you load a shared settings or helper file. Here is settings.ps1:
# settings.ps1 - shared settings for the deployment scripts
$Environment = 'staging'
function Get-ConnectionString { "Server=db01.$Environment.internal;Database=orders" }Running it normally, then dot-sourcing it:
./settings.ps1
"Environment: [$Environment]"
. ./settings.ps1
"Environment: [$Environment]"
Get-ConnectionStringEnvironment: []
Environment: [staging]
Server=db01.staging.internal;Database=ordersThe first run set $Environment in a child scope that was thrown away. The dot and the
space after it are both required. For anything bigger than a settings file, a module is the
better tool; see Scripts, Scope, and Modules.
Splatting with @
Splatting passes a hashtable of parameter names and values to a command. Write @params
instead of $params:
$params = @{
Path = './logs'
Filter = '*.log'
Recurse = $true
}
Get-ChildItem @params | Select-Object -ExpandProperty Nameapp.log
app-2026-11-01.logSwitch parameters take $true. Splatting shines when parameters depend on conditions: build
the hashtable, add keys as needed, then make one call. You can also mix splatted and normal
parameters:
$params = @{ Path = './logs'; Filter = '*.log' }
$params.Recurse = $true
Get-ChildItem @params -File | Measure-Object | Select-Object -ExpandProperty Count2An array splats as positional arguments, which is the tidy way to build an argument list for a native program:
$tarArgs = '-czf', 'logs.tgz', './logs'
tar @tarArgs && tar -tzf logs.tgz./logs/
./logs/app.log
./logs/notes.txt
./logs/archive/
./logs/archive/app-2026-11-01.logHashtables themselves are covered in Arrays, Hashtables, and Custom Objects.
Redirection operators
PowerShell has six output streams, and each one can be redirected by number:
| Stream | Number | Written by | Redirect to file | Merge into output |
|---|---|---|---|---|
| Success | 1 | normal output, Write-Output | > or 1> | |
| Error | 2 | Write-Error, failed commands | 2> | 2>&1 |
| Warning | 3 | Write-Warning | 3> | 3>&1 |
| Verbose | 4 | Write-Verbose | 4> | 4>&1 |
| Debug | 5 | Write-Debug | 5> | 5>&1 |
| Information | 6 | Write-Information, Write-Host | 6> | 6>&1 |
| All | * | everything | *> | *>&1 |
> overwrites, >> appends:
Get-ChildItem ./logs -Name > listing.txt
Get-Content listing.txt
'second line' >> listing.txt
Get-Content listing.txtarchive
app.log
notes.txt
archive
app.log
notes.txt
second lineRedirecting individual streams lets a script keep errors and warnings in separate files while normal output still reaches the screen:
function Invoke-Step {
Write-Output 'output: step done'
Write-Error 'error: disk quota exceeded'
Write-Warning 'warning: retrying'
Write-Verbose 'verbose: 3 files copied' -Verbose
Write-Information 'info: took 2.1 s' -InformationAction Continue
}
Invoke-Step 2> errors.txt 3> warnings.txt
'--- errors.txt'
Get-Content errors.txt
'--- warnings.txt'
Get-Content warnings.txtoutput: step done
VERBOSE: verbose: 3 files copied
info: took 2.1 s
--- errors.txt
Invoke-Step:
Line |
8 | Invoke-Step 2> errors.txt 3> warnings.txt
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| error: disk quota exceeded
--- warnings.txt
warning: retrying2>&1 merges errors into the success stream so you can capture both in a variable. The
errors arrive as ErrorRecord objects, not strings:
function Invoke-Step {
Write-Output 'output: step done'
Write-Error 'error: disk quota exceeded'
}
$out = Invoke-Step 2>&1
$out.Count
$out | ForEach-Object { $_.GetType().Name }2
String
ErrorRecordTo throw output away, redirect to $null. For method calls that return a value you do not
want (HashSet.Add() returns True or False), there are four common spellings:
$set = [System.Collections.Generic.HashSet[string]]::new()
$set.Add('web01')
$set.Add('web02') > $null
[void]$set.Add('web03')
$null = $set.Add('web04')
$set.Add('web05') | Out-Null
$set.CountTrue
5All four discard the value. $null = and [void] are the fastest; | Out-Null is the
slowest in a tight loop because it starts a pipeline.
File encoding differs between versions
The bytes > writes depend on your PowerShell version. In PowerShell 7:
'ok' > enc.txt
([IO.File]::ReadAllBytes("$PWD/enc.txt") | ForEach-Object { '{0:X2}' -f $_ }) -join ' '6F 6B 0AThat is UTF-8 without a byte order mark. I ran the same two lines in Windows PowerShell 5.1
(launched with powershell.exe -NoProfile) and got FF FE 6F 00 6B 00 0D 00 0A 00: UTF-16LE
with a BOM and Windows line endings. Plenty of Linux tools, and some config parsers, choke on
that. If a 5.1 script writes a file another program reads, use
Out-File -Encoding utf8 or Set-Content -Encoding utf8 instead of >.
Where you'll use this
A nightly backup job writes one pipe-delimited line per backup: finish time, host, type, size in bytes, status, duration in seconds.
2026-11-08T23:00:04Z|db01|full|5368709120|OK|1832
2026-11-08T23:30:11Z|db02|full|5905580032|OK|2011
2026-11-08T23:45:02Z|files01|incremental|734003200|FAILED|45
2026-11-09T00:10:40Z|mail01|incremental|1288490188|OK|388The on-call engineer wants a readable report each morning, with failures and suspiciously small backups called out. This script uses nearly every operator in the article:
# backup-report.ps1 - turn the backup tool's pipe-delimited log into a readable report
param([string]$LogPath = './backup.log')
$minSizeGB = $env:BACKUP_MIN_GB ?? 1 # environment override, default 1 GB
$rows = '{0,-16} {1,-8} {2,-12} {3,8} {4,9} {5}'
$failed = @()
$rows -f 'Finished (UTC)', 'Host', 'Type', 'Size', 'Duration', 'Status'
foreach ($line in Get-Content $LogPath) {
$when, $server, $type, $bytes, $status, $seconds = $line -split '\|'
$finished = ([datetimeoffset]$when).UtcDateTime
$sizeGB = [double]$bytes / 1GB
$duration = [timespan]::FromSeconds($seconds)
$note = $sizeGB -lt $minSizeGB ? ' (small)' : ''
if ($status -ne 'OK') { $failed += $server }
$rows -f ('{0:yyyy-MM-dd HH:mm}' -f $finished), $server, $type,
('{0:N1} GB' -f $sizeGB), ('{0:hh\:mm\:ss}' -f $duration), "$status$note"
}
''
$failed.Count -eq 0 ? 'All backups succeeded.' : "FAILED: $($failed -join ', ')"./backup-report.ps1Finished (UTC) Host Type Size Duration Status
2026-11-08 23:00 db01 full 5.0 GB 00:30:32 OK
2026-11-08 23:30 db02 full 5.5 GB 00:33:31 OK
2026-11-08 23:45 files01 incremental 0.7 GB 00:00:45 FAILED (small)
2026-11-09 00:10 mail01 incremental 1.2 GB 00:06:28 OK
FAILED: files01The pieces: -split '\|' with multiple assignment unpacks each line (escaped, because |
is a regex metacharacter); one template string with alignment keeps the header and rows in
step; nested -f calls format the date, size and duration; ?? gives the threshold a
default; the ternary picks the note and the final message; -join lists the failed hosts.
Because the threshold comes from the environment, a scheduled task can tighten it without
editing the script, and > saves the report for an email step:
$env:BACKUP_MIN_GB = 2
./backup-report.ps1 > report.txt
Get-Content report.txt | Select-Object -Last 32026-11-09 00:10 mail01 incremental 1.2 GB 00:06:28 OK (small)
FAILED: files01The same building blocks turn up in release-notes generators (-replace ticket IDs with
links, -join the lines), CSV-to-config converters, chat notifications, and any script
that parses the output of a tool that only speaks text.
Common mistakes
Splitting on . or | without escaping. '10.0.4.17' -split '.' returns ten empty
strings because the delimiter is a regex. Use '\.', '\|', [regex]::Escape($delim), or
the SimpleMatch option.
Capture group references in double quotes. -replace '(\d{4})-(\d{2})-(\d{2})', "$3/$2/$1"
returns //, because PowerShell expanded $3 and friends as variables first. Use single
quotes, or escape them as `$1.
Passing -f to a command instead of an expression. In argument mode, -f looks like a
parameter name. With Write-Host it matches -ForegroundColor:
Write-Host '{0} is down' -f 'web01'Write-Host: Cannot bind parameter 'ForegroundColor'. Cannot convert value "web01" to type "System.ConsoleColor". Error: "Unable to match the identifier name web01 to a valid enumerator name. Specify one of the following enumerator names and try again:
Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White"Wrap the expression in parentheses: Write-Host ('{0} is down' -f 'web01') prints
web01 is down. The same applies to -split, -replace and -join used as arguments.
Forgetting braces with ?.. $response?.StatusCode reads a variable named
response? and quietly returns nothing. Write ${response}?.StatusCode.
Using && after a cmdlet that returns $false. Test-Path /nope && 'found it' prints
both False and found it. The chain operators look at success, not at the value.
Writing files with > in Windows PowerShell 5.1. You get UTF-16LE with a BOM. Use
Out-File -Encoding utf8 when another program will read the file.
Summary
-ffills{index,alignment:format}placeholders:{0,-12}left-aligns in 12 columns,{1:N2}formats a number,{2:yyyy-MM-dd}a date. Output follows the current culture.- Interpolation needs
$( )for properties and expressions, and${name}before a colon. -splittakes a regex (escape.and|), an optional maximum number of pieces (-split '=', 2) and options such asSimpleMatch; unary-splitsplits on whitespace.-joinuses each element'sToString(); join a property ($objs.Name -join ', ') rather than the objects. Unary-joinneeds parentheses around an inline list.-replaceis regex-based, replaces every match and supports$1and${name}captures. Keep the replacement in single quotes..Replace()is the literal, case-sensitive alternative.- PowerShell 7 adds
?:,??,??=,?.and?[](variable names in braces), and&&/||, which test success ($?or the exit code), not the returned value. None of them parse in Windows PowerShell 5.1. &runs a command from a string or script block in a child scope;. ./file.ps1runs it in the current scope;@paramssplats a hashtable (named) or array (positional).- Streams 1 to 6 can be redirected separately (
2>,3>,*>), merged with2>&1, or discarded with$null. In 5.1,>writes UTF-16LE.
Exercises
Print one aligned line per service: the name left-aligned in 14 columns, the p95 latency
right-aligned in 10 columns with thousands separators and no decimals followed by ms, and
the request count right-aligned in 12 columns with separators followed by req.
$services = @(
[pscustomobject]@{ Name = 'checkout-api'; P95Ms = 182.4; Requests = 1250331 }
[pscustomobject]@{ Name = 'search'; P95Ms = 1043.9; Requests = 88412 }
[pscustomobject]@{ Name = 'auth'; P95Ms = 41.27; Requests = 2210988 }
)Show Solution
foreach ($s in $services) {
'{0,-14}{1,10:N0} ms{2,12:N0} req' -f $s.Name, $s.P95Ms, $s.Requests
}checkout-api 182 ms 1,250,331 req
search 1,044 ms 88,412 req
auth 41 ms 2,210,988 reqN0 rounds as well as adding separators, which is why 1043.9 shows as 1,044.
A line from a .env file reads SMTP_PASSWORD=pa=ss:word==. Split it into $key and
$value so that the value keeps every = it contains, and print both in brackets.
Show Solution
$line = 'SMTP_PASSWORD=pa=ss:word=='
$key, $value = $line -split '=', 2
"key=[$key] value=[$value]"key=[SMTP_PASSWORD] value=[pa=ss:word==]The 2 stops -split after the first delimiter. Base64 values and connection strings
routinely contain =, so always cap the split when parsing key=value data.
A legacy tool writes dates as dd/MM/yyyy. Rewrite every date in this log to
yyyy-MM-dd with a single -replace:
$log = @'
09/11/2026 02:00:01 backup started
09/11/2026 02:31:44 backup finished
10/11/2026 02:00:03 backup started
'@Hint
Capture day, month and year in three groups, then reorder them in a single-quoted replacement string.
Show Solution
$log -replace '(\d{2})/(\d{2})/(\d{4})', '$3-$2-$1'2026-11-09 02:00:01 backup started
2026-11-09 02:31:44 backup finished
2026-11-10 02:00:03 backup started-replace replaces every match in the here-string, not just the first. ISO dates sort
correctly as text, which is the whole point of converting them.
Build a $settings hashtable where Port comes from $env:APP_PORT with a default of
8080 and LogLevel from $env:APP_LOG_LEVEL with a default of Information. Then give it
a Region of eu-west-1 only if it does not have one yet. Test with APP_PORT unset and
APP_LOG_LEVEL set to Debug. (PowerShell 7.)
Show Solution
$env:APP_PORT = $null
$env:APP_LOG_LEVEL = 'Debug'
$settings = @{
Port = $env:APP_PORT ?? 8080
LogLevel = $env:APP_LOG_LEVEL ?? 'Information'
}
$settings.Region ??= 'eu-west-1'
$settings.Port
$settings.LogLevel
$settings.Region8080
Debug
eu-west-1Setting an environment variable to $null removes it, so ?? falls back to 8080. ??=
works on hashtable entries too: a missing key reads as $null. Remember that a value from
the environment is a string ('8080'), while the default is an integer; cast with [int]
if you compare or do arithmetic with it.
Create a dated archive name like logs-20261109.tgz with -f, build the tar arguments
as an array and splat them, send tar's error output to tar-errors.txt, and use && and
|| to print either created <name> or tar failed: <error text>. Test it once with
./logs and once with a directory that does not exist.
Show Solution
$archive = 'logs-{0:yyyyMMdd}.tgz' -f (Get-Date '2026-11-09')
$tarArgs = '-czf', $archive, './logs'
tar @tarArgs 2> tar-errors.txt && "created $archive" || "tar failed: $(Get-Content tar-errors.txt)"
$tarArgs = '-czf', $archive, './no-such-dir'
tar @tarArgs 2> tar-errors.txt && "created $archive" || "tar failed: $(Get-Content tar-errors.txt)"created logs-20261109.tgz
tar failed: /usr/bin/tar: ./no-such-dir: Cannot stat: No such file or directory /usr/bin/tar: Exiting with failure status due to previous errorsI used a fixed date so the output is reproducible; in a real job use (Get-Date).
$(Get-Content ...) inside the string joins the two error lines with a space. Note that
tar still created (an empty) archive in the failed run; the exit code, not the presence
of the file, tells you whether it worked.
Tested with: PowerShell 7.6.9 on Ubuntu 24.04 (WSL2) and Windows PowerShell 5.1
(5.1.26100) on Windows 11, November 2026. Every PowerShell 7 example was piped into
pwsh -NoProfile exactly as shown; the 5.1 notes (parse errors for the PowerShell 7
operators, .Split('--'), the .Replace() overload, character ranges, > encoding and
the en-US percent format) come from running those lines in Windows PowerShell 5.1 on the
host. The lab used the invariant culture, so your number formatting may differ slightly.
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every PowerShell tutorial here is tested end to end before publishing.