I mainly code with PowerShell and 85% of my scripts are built with it.
The more I go on and code, the more I realize that I always use IF statements, which to be fair are sometimes needed, but since I put a lot of checks and throws in my code I find my scripts full of these statements. What's a different logical approach that I could take?
I tried looking online and found Ternary Operators but couldn't find good documentation for PowerShell.
Assuming you're using PowerShell (Core) 7+, you can use the following constructs to avoid the need for if
statements in simple cases:
?:
, the ternary conditional operator
# Alternative to:
# $foo = if ($true) { 'bar' } else { 'baz' }
$foo = $true ? 'bar' : 'baz'
??
, the null-coalescing operator
# Alternative to:
# $foo = if ($null -ne $possiblyNull) { $possiblyNull } else { 'default' }
$foo = $possiblyNull ?? 'default'
?.
, the null-conditional operator
# Alternative to:
# if ($null -ne $possiblyNull) { $possiblyNull.ToString() }
${possiblyNull}?.ToString()
Note the - unfortunate - need to enclose the variable name in {...}
for ?.
to work as intended, because - surprisingly - ?
is a legal character in a PowerShell variable name.
GitHub #11379 asks for this obscure requirement to be lifted, based on analysis that shows that only very little existing code, if any, would be impacted by interpreting a trailing ?
as part of ?.
rather than as part of the variable name. Sadly, despite claims to revisit the issue - see GitHub issue #14025 - no action was ever taken.
Also note that while .?
tests the object itself for being $null
, there is currently no way to conditionally access an object's property that may or may not exist.
$null
if you access a non-existent property (e.g., $PSCulture.NoSuchProperty
), it does matter when Set-StrictMode
-Version 2
or higher is in effect, in which case attempts to access a non-existent property fail (which the current implementation of ?.
does not prevent).?.