RaG*_*aGe 4 powershell null-conditional-operator
C#和其他语言通常有空条件?.
A?.B?.Do($C);
Run Code Online (Sandbox Code Playgroud)
当 A 或 B 为空时不会出错。我如何在 powershell 中实现类似的功能,有什么更好的方法可以做到:
if ($A) {
if ($B) {
$A.B.Do($C);
}
}
Run Code Online (Sandbox Code Playgroud)
Powershell 7 Preview 5 具有处理空值的运算符。https://devblogs.microsoft.com/powershell/powershell-7-preview-5/
$a = $null
$a ?? 'is null' # return $a or string if null
is null
$a ??= 'no longer null' # assign if null
$a ?? 'is null'
no longer null
Run Code Online (Sandbox Code Playgroud)
编辑:Powershell 7 Preview 6 堆在更多新运算符上:https : //devblogs.microsoft.com/powershell/powershell-7-preview-6/。由于变量名可以有一个“?” 在名称中,您必须用花括号将变量名称括起来:
${A}?.${B}?.Do($C)
Run Code Online (Sandbox Code Playgroud)
正如Mathias R. Jessen 的回答指出的那样,PowerShell默认情况下对于属性访问具有 null 条件访问行为(null-soaking) [1];例如,$noSuchVar.Prop悄悄返回$null
js2010 的答案显示了相关的空合并运算符 ( ??) /空条件赋值运算符 ( ??=),它们在 PowerShell [Core] v 7.1+ 中可用
但是,直到 PowerShell 7.0:
没有办法以空条件忽略方法调用:$noSuchVar.Foo()总是失败。
同样,没有办法以空条件忽略(数组)索引:$noSuchVar[0]总是失败。
如果您选择使用更严格的行为Set-StrictMode,则即使属性访问空浸泡也不再是一个选项:使用Set-StrictMode -Version 1或更高版本$noSuchVar.Prop会导致错误。
在PowerShell [Core] 7.1+中,可以使用null 条件(null-soaking)运算符:
新的运营商:
原则上与 C#具有相同的形式:?.并且?[...]
但是 -从 v7.1 开始-需要将变量名称括在{...}
也就是说,您当前不能仅使用$noSuchVar?.Foo(), $A?.B, 或$A?[1],您必须使用
${noSuchVar}?.Foo(), ${A}?.B, 或${A}?[1]
这种繁琐语法的原因是存在向后兼容性问题,因为?是变量名称中的合法字符,因此如果不使用来消除变量名称的歧义,假设的现有代码$var? = @{ one = 1}; $var?.one可能会中断;{...}实际上,这种使用非常罕见。
如果您认为不妨碍新语法比可能破坏变量名以 结尾的脚本更重要,请在此 GitHub 问题?上发表您的意见。
[1] PowerShell 的默认行为甚至提供存在条件属性访问;例如,$someObject.NoSuchProp悄然归来$null。
PowerShell 没有空条件运算符,但它会默默地忽略空值表达式上的属性引用,因此您可以“跳到”链末尾的方法调用:
if($null -ne $A.B){
$A.B.Do($C)
}
Run Code Online (Sandbox Code Playgroud)
可在任何深度工作:
if($null -ne ($target = $A.B.C.D.E)){
$target.Do($C)
}
Run Code Online (Sandbox Code Playgroud)