Powershell 'x or y' assignment Powershell 'x or y' assignment powershell powershell

Powershell 'x or y' assignment


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


So a simple method for reducing this:

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

Would be to use the fact that true and false are just one or zero and could be used as an array index like so:

$a =  @($c, $b)[$b -ne $null]