Powershell – How to Get (gci).count to Return Numeric Values for Empty or Single-Item Lists

powershell

Related:
How can I write a script to count files modified within a particular month?

When I try to get a count of items, e.g. with (gci).count to count files in a folder, PowerShell returns no output for empty lists or lists containing only one item. It works fine for lists containing multiple items, though.

enter image description here

How can I get PowerShell to return proper numeric values for all cases? i.e.: How can I get it to output an actual zero for empty lists, and output one for single-item lists?

My particular use case, as further described in the related question linked above, is to get a count of items in a list that results from piping a gci command's output to where.

Best Answer

This has to do with the fact that powershell, when returning an array of 1 item will simply collapse the array into that single item.

Before version 3, this would result is an object without the expected count property and your result would be empty. This has been "fixed" in version 3.

So you have 2 options:

  1. Upgrade to Powershell v3
  2. Apply the following workaround where you always wrap your results as an array type @():

    @(gci).count

Related Question