Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm new to PowerShell and have a question on the following behaviour. I'm trying to count the number of files in a directory of a certain type. If there are some, I will then copy them elsewhere. Here's the output of my test folder; the code is modified from MSDN examples I found:

[PS]> Get-ChildItem c:\pstdump

Directory: C:\pstdump

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         2/12/2011   9:48 AM          0 blah.pst
-a---         2/12/2011   9:36 AM          0 New Text Document.txt
-a---         2/12/2011   9:36 AM         20 New WinRAR archive.rar

[PS]> (Get-ChildItem c:\pstdump).Count

All well and good; PowerShell and I are in agreeance that there are 3 files in the folder. Now when I'd like to pick particular file types (for example .PST files):

[PS]> Get-ChildItem c:\pstdump -filter "*.pst"

Directory: C:\pstdump

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         2/12/2011   9:48 AM          0 blah.pst

[PS]> (Get-ChildItem c:\pstdump -filter "*.pst").Count

The '.Count' is returning nothing even though the filter should be returning 1 file. I consider this an incorrect count...

Could someone please explain why this 'incorrect' .Count is being returned?

Alternatively, please feel free to berate me for the obvious n00b mistake I must be making.


share|improve this question
up vote 5 down vote accepted

Call it a quirk or a feature, but this has to do with how PowerShell deals with lists that are only 1 in length. It "flattens" them so that it is no longer a list, but a single FileInfo object. Since the FileInfo object doesn't have a Count property, you get no result. There are a couple of ways to work around this:

  1. Force the value returned to remain as an array, by wrapping it in the array operator @():

    @(Get-ChildItem c:\pstdump -filter "*.pst").Count
  2. Use the Measure-Object cmdlet:

    (Get-ChildItem c:\pstdump -filter "*.pst" | measure).Count
share|improve this answer
Brilliant! Just slapped the '@' in front and the array count is working as expected. Thanks for the answer! – Beeblebrox Dec 2 '11 at 5:31

I was trying to get the number of file types within a directory to decide whether to process the folder or not.

While the above works, a better solution may be to use Test-Path to check for the existance of specific files or file types.

share|improve this answer

Your Answer


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.