Converting Results into Arrays

by Nov 18, 2008

Whenever you call a function or cmdlet, PowerShell uses a built-in mechanism to handle results:

  1. If no results are returned, PowerShell returns nothing
  2. If exactly one result is returned, the result is handed to the caller
  3. If more than one result is returned, all results are wrapped into an array, and the array is returned.

As such, you never really know what you are getting. For example, Get-ChildItem (alias: Dir) returns nothing, a file object, a folder object or an array, depending on the folder you are listing:

(Dir C:nonexistent).GetType()
(Dir C:autoexec.bat).GetType()
(Dir $env:windir).GetType()

With a little trick, you can force PowerShell to always return an array. This way, you can easily find out how many elements were returned. Simply wrap the command into @():

@(Dir C:nonexistent).GetType()
@(Dir C:autoexec.bat).GetType()
@(Dir $env:windir).GetType()
@(Dir C:nonexistent).Count
@(Dir C:autoexec.bat).Count
@(Dir $env:windir).Count

You will still receive red error messages when you try and list a folder that does not exist. To get rid of these error messages, set the ErrorAction parameter to SilentlyContinue:

@(Dir C:nonexistent -EA SilentlyContinue).Count