Calling -split on an empty string results in an array with one element which is an empty string. I expect it to return a zero-length array or a $Null which is not an array.
What am I doing wrong?
# split an empty string
$a = '' -split ','
# the result is an array with one element which is an empty string:
$a -is [array] # true
$a.Count # 1
"a[0]='$($a[0])'" # result: a[0]=''
EDIT: from the comments, people ask how is the empty string different from a string with no comma at all, eg:
$s = 'a'
$s -split ','
# returns 'a'
It returns "the first element of the array expressed as a string" which is the string 'a'.
So in the case of an empty string, It also returns "the first element of the array expressed as a string" which is in this case the empty string.
So I guess it's the round round trip through -join that seems not consistent. If you -join then -split a zero-element array, you don't get a zero-element array back. This seems asymmetrical.
# empty array
$a_src = @()
$a_src.Count
# returns 0
# join
$a_src_str = $a_src -join ','
"a_src_str='$a_src_str'" # empty string
# then split
$a = $a_src_str -split ','
# non-empty array
$a.Count
# returns 1
So I guess the problem is that two array states collapse into the same "array expressed as string" so state is lost, so -split can never decide the original state. Both a zero-length array, and an array of 1 whose element is the empty string, when -join'ed both result in the same state--an empty string.
# array of zero elements
$a_empty = @()
$a_empty_str = $a_empty -join ','
"a_empty_str='$a_empty_str'" # empty string
# array of one element an empty string
$a_one = @('')
$a_one_str = $a_one -join ','
"a_one_str='$a_one_str'" # empty string
I suppose if you needed this round trip to work (I do) you'd have to create and manage another bit of state to differentiate.
[also, a meta side: I posted this 11pm one day, and 9am the next day it was already closed. Sorta all happened when I was sleeping ;)]
EDIT:
It's not just "join". Any feature that expresses items as a list in a string separated by commas is going to be misrepresented by -split.
Here's one: wsman (WinRM) TrustedHosts:
get-item 'wsman:\localhost\client\trustedhosts'
# returns
('node1,node2' -split ',').Count # 2
('node1' -split ',').Count # 1
('' -split ',').Count # 1 (not 0)
$nullor an empty array here? What you're describing is the exact same behavior as in'a' -split ',': the first array element contains the first matcha. In the case of an empty string as input, the first array element also contains the first match: an empty string. This is exactly what I would expect.-splitoperator will split on any matching delimiter ... and return the result in a string array. any delimiter will give the same result since the result of the split will ALWAYS be stuffed into a string array.