Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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

share|improve this answer
    
You particularly call out arrays of 1 item in your answer - does the fix work for empty arrays as well? Also, wouldn't that workaround be @((gci).count)? –  Iszi Aug 9 '13 at 19:14
    
Hrm. Interesting. Your initial description of the workaround doesn't quite match up with the actual usage. And the usage itself is a bit confusing in that it doesn't actually need any extra parenthesis. Good news is, it works for empty arrays also. –  Iszi Aug 9 '13 at 19:22
2  
@Iszi The workaround works in the general case since the @() denotes an array object which always has a count property. The contents of the array is populated with the results of gci. An array can be empty, so if gci return nothing, you get an empty array. You also don;t need any more brackets than I show, powershell will know that gci is a complete expression in this context. –  zdan Aug 9 '13 at 22:36

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.