Force Powershell functions to array, ALWAYS, and ensure no zero / empty results

One thing that annoys me in Powershell is it’s tendency to automatically cast arrays with 1 object to a normal object, thus you can’t do $array[0] anymore or use .Count (unless using PS v3+).

You can’t really ensure your methods/functions always return a proper array, they might be empty or they might have been converted to an object. Here’s how to force anything into an array, always, and to make sure there are no ’empty’ objects that mess up the array’s count property:

[Array]$result = @(myFunctionCall | where {$_})
[Array] and @() make sure that $result becomes an array, while | where {$_} ensures that there are no empty values ๐Ÿ™‚