Ok, recently I was looking for a way to null coalesce in PowerShell, and I ran into this post: Null coalescing in powershell.
I saw the comment by @Zenexer, and was intrigued. Here was the syntax:
Clear-Host
#expected one
"Test 1: " + ("one", "two", 1 -ne $null)[0]
#expected two
"Test 2: " + ($null, "two", 1 -ne $null)[0]
This works perfectly. However, a co-worker (Walter Puckett) and I were very interested and did some more digging into the syntax and found some real weirdness.
Before I get into the weirdness, can anyone point to any documentation that explains this syntax?
## 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()
Lessons learned:
- The test should go into the very last element of the array
- The test should not be wrapped with parens as it will break the coalesce
- The default value MUST be on the left side of the test, or be hard coded as the second to last item in the array
- We tested with numbers and and a simple object test, so it should work for any type of object