Control Flow
Falsy Values
$false
$null
- Empty string
- Numeric zeros
- Empty collections implemented
IList
. - Single-item collection that contains falsy value,
@(0)
,@($null)
for example.
NOTE
You can cast falsy values to boolean.
[bool]@() # False
Newline Indicator
Use `
to indicate a new line if you do want to finish a long command invocation across multiple lines.
gci `
-File `
-Filter '*.mp4'
2
3
WARNING
A space is required before the backtick.And no any chacracter is allowed after the backtick.
TIP
Stop using backticks! They're ugly! Use hashtable splatting instead.
$table = @{
Filter = '*.mp4';
File = $true
}
gci @table
2
3
4
5
Multi-Line Piping
Trailing Piper
In multiple piping, we can use trailing |
to indicate the new line, PowerShell regconizes these lines as a whole command piping.
gps |
foreach CPU |
sort -desc
2
3
Leading Piper PowerShell 7+
Starting with PowerShell 7, |
is allowed as the first non-space chacracter in a new line.
gps | foreach CPU
| sort -desc # [!code highlight]
2
Command Chaining
Multi-Command in Single Line
Use ;
to separate commands in the same line. All commands are executed in order.
cd ..; gci -rec -file; echo hello
Chaining And & Or PowerShell 7+
In PowerShell 7, &&
and ||
were introduced to do the same command chaining as bash does.
Null-Conditional Operator PowerShell 7+
This feature is basically the same as in C#
except a bracing {}
is required around variable because ?
is valid as part of variable name.
$null.Bar() # exception raised
${null}?.Bar() # ok
$null[0] # exception raised here
${null}?[0] # ok
$null ?? 'I am not null'
$baz ??= 'I am new value'
2
3
4
5
6
7
8
9
Ternary Operator PowerShell 7+
No need to explain, same as in C#
.
Pattern Matching
Switch statement behaves similarly when the input is a singular object but can enumerate when the input is a collection. It has a few different patterns available:
- Constant: matching by primitive literal.
- Type: matching by target type with
-is
operator. - Regex: matching by regex string, specifically for
string
. - Wildcard: matching by wildcard string, specifically for
string
.