更新:
PowerShell v6- 解决方案:
您要查找的是 null-coalescing,PowerShell 在 v7.0.0-preview.4 中没有此功能。
目前,必须这样做:
$contentDir = if ($null -eq $config.contentDir) { 'content' } else { $config.contentDir }
注意:$null 被故意放置在 -eq 的 LHS 上以明确测试 $null,因为作为 RHS,如果值为test 恰好是 array-valued.
对Lee Daily's array-based answer 的改编可实现更简洁的解决方案:
$contentDir = ($config.ContentDir, 'content')[$null -eq $config.ContentDir]
使用将在 v7.0 中实现的ternary operator (conditional) 可以实现同样简洁的等效项:
$contentDir = $null -eq $config.contentDir ? 'content' : $config.contentDir
但是,所有这些方法都有以下不受欢迎的方面:
定义一个名为??的自定义函数可以解决这些问题:
# Custom function that emulates null-coalescing.
function ?? ($PossiblyNull, $ValueIfNull) {
if ($null -eq $PossiblyNull) { $ValueIfNull } else { $PossiblyNull }
}
$contentDir = ?? $config.contentDir 'content'
但是,这样的自定义函数有缺点:
自定义函数的缺点是:
如果实现this GitHub feature request,您将能够使用真正的空合并,这既是最简洁的解决方案,又避免了上述情况不良方面:
# Hopefully soon
$contentDir = $config.contentDir ?? 'content'
在链接的 GitHub 问题中还提出了一个相关功能是 null-conditional assignment,$config.ContentDir ?= 'content'