Powershell'x或y'赋值

kfs*_*one 11 powershell ternary-operator null-coalescing-operator powershell-core

有几种语言可以提供默认或逻辑或分配机制:

a = b || c;
a = b or c
a="${b:-$c}"
a = b ? b : c;
Run Code Online (Sandbox Code Playgroud)

到目前为止,我在Powershell Core中找到的唯一等价物是非常冗长:

$a = if ($b) { $b } else { $c }
Run Code Online (Sandbox Code Playgroud)

在某些情况下必须成为

$a = if ($b -ne $null) { $b } else { $c }
Run Code Online (Sandbox Code Playgroud)

有没有更好的选择[编辑:],这不会牺牲可读性?

Mat*_*sen 9

||PowerShell赋值中没有短路运算符,也没有与Perl的//"定义或"运算符等效的东西- 但是你可以构造一个简单的null coalesce模仿,如下所示:

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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后使用像:

$a = ?? $b $c
Run Code Online (Sandbox Code Playgroud)

或者,如果你想$true在第一个例子中返回任何已经评估过的东西:

$a = ?? $b $c -Truthy
Run Code Online (Sandbox Code Playgroud)