Sometimes you’ll need to run a command with the same input with different logic.
This can be a hassle using a slow command like Get-ADUser
or Get-ChildItem
on a lot of files like ~
(Home) with -Depth
/ -Recurse
ls ~ -Depth 4 | Format-Table Name
PowerShell 7.0+
Powershell 7 added the Ternary Operator, and several operators for handling $null
values.
All of these examples will only run Get-ChildItem
the first time. Any future calls are cached.
Null-Coalesce ??=
Assignment Operator
This is my favorite on the Command line. The RHS
(Right Hand Side) skips evaluation if the left side is not $null
$AllFiles ??= ls ~ -Depth 4
Using the Null-Coalesce ??
Operator
$AllFiles = $AllFiles ?? ( ls ~ -Depth 4 )
Ternary Operator ? whenTrue : WhenFalse
$allFiles = $allFiles ? $allFiles : ( ls ~ -Depth 4 )
Windows PowerShell
and Powershell < 7
Windows Powershell can achieve the same effect with an if statement
if(! $AllFiles) { $AllFiles = ls ~ -Depth 4 }