I have a variable $try that contains an array, and I want $res to contain the sorted version of $try. This seems easy enough, but I can't get this to work when $try happens to contain an empty array.
When $try contains a non-empty array, no problem:
PS C:\data> $try = @("a", "c", "b")
PS C:\data> $res = $try | Sort-Object
PS C:\data> $res
a
b
c
PS C:\data> $res.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
However, when the input array is empty, the output object is $null, not (as I would have expected) an empty array:
PS C:\data> $try = @()
PS C:\data> $res = $try | Sort-Object
PS C:\data> $res
PS C:\data> $null -eq $res
True
PS C:\data> $null -eq $try
False
I want $res to be the sorted version of $try, even if $try happens to contain an empty array. In that case, I want $res to also be an empty array.
Is there a way of doing this other than something like:
PS C:\data> $try = @()
PS C:\data> if ($try) {$res = $try | Sort-Object} else { $res = @() }
PS C:\data> $null -eq $try
False
PS C:\data> $null -eq $res
False