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 🙂

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
James
James
4 years ago

Thanks for this, been beating my head against a wall for a week or so now!