【发布时间】:2019-12-22 00:23:30
【问题描述】:
好的,最近我正在寻找一种在 PowerShell 中进行 null 合并的方法,结果遇到了这个帖子:Null coalescing in powershell。
我看到@Zenexer 的评论,很感兴趣。这是语法:
Clear-Host
#expected one
"Test 1: " + ("one", "two", 1 -ne $null)[0]
#expected two
"Test 2: " + ($null, "two", 1 -ne $null)[0]
这非常有效。然而,我和一位同事 (Walter Puckett) 非常感兴趣,并且对语法进行了更多挖掘,发现了一些真正的怪异之处。
在我进入奇怪之处之前,任何人都可以指出任何解释这种语法的文档吗?
## THE WEIRDNESS:
# it does not matter what the number is evidently
"Test 3: " + ($null, "two", 8675309 -ne $null)[0]
# reversing the comparison test breaks the coalesce
"Test 4: " + ($null, "two", $null -ne 1)[0]
# Moving the test into the middle of the array evidently cuts the array off
"Test 5: " + ($null, 1 -ne $null, "two").Length
# Moving the test into the middle of the array evidently cuts the array off,
# UNLESS you wrap the test with parens
"Test 6: " + ($null, (1 -ne $null), "two").Length
# The number used in the test is returned for the array value at that index
"Test 7: " + ($null, $null, 8675309 -ne $null)[0]
# The number used in the test is returned for the array value at that index,
# UNLESS you wrap the test with parens
"Test 8: " + ($null, $null, (8675309 -ne $null))[0]
# wrapping the test with parens will break the coalesce
"Test 9: " + ($null, "two", (1 -ne $null))[0]
# if all elements are null, the default value will be the value on the left
# side of the test
"Test 10: " + ($null, $null, 123456789 -ne $null)[0]
# test with an object
$conn = New-Object System.Data.SqlClient.SqlConnection
"Test 11: " + ($null, $conn, 1 -ne $null)[0].GetType()
经验教训:
- 测试应该进入数组的最后一个元素
- 不应使用括号包裹测试,因为它会破坏合并
- 默认值必须位于测试的左侧,或者硬编码为数组中倒数第二项
- 我们使用数字和简单的对象测试进行了测试,因此它应该适用于任何类型的对象
【问题讨论】:
标签: powershell