Powershell or assignment

  • A+

There are several languages that provide either a defaulting or logical or mechanism for assignment:

a = b || c; a = b or c a="${b:-$c}" a = b ? b : c; 

So far the only equivalent I've found in Powershell Core is the exceedingly verbose:

$a = if ($b) { $b } else { $c } 

which in some cases has to become

$a = if ($b -ne $null) { $b } else { $c } 

Is there a better alternative?


There's no || short-circuit operator in PowerShell assignments, and nothing equivalent to Perl's // "defined-or" operator - but you can construct a simple null coalesce imitation like so:

function ?? {   param(     [Parameter(Mandatory=$true,ValueFromRemainingArguments=$true,Position=0)]     [psobject[]]$InputObject,      [switch]$Truthy   )    foreach($object in $InputObject){     if($Truthy -and $object){       return $object     }     elseif($object -ne $null){       return $object     }   } } 

Then use like:

$a = ?? $b $c 

or, if you want to just have return anything that would have evaluated to $true like in your first example:

$a = ?? $b $c -Truthy 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: