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 🙂

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
James Recent comment authors

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

  Subscribe  
newest oldest most voted
Notify of
James
Guest
James

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