Using Get-ChildItem Results in PowerShell

A colleague had a problem using Get-ChildItem in PowerShell.

Screenshot from Microsoft Docs Page

It would return results just fine but there was some confusion over what *exactly* was being returned. The issue arose because sometimes, when you did this:

it would return a number and sometimes it wouldn’t, coinciding with whether there were none, one or more files.

Can you guess why?

To understand what is going on, you need to realise that what this commandlet returns isn’t always going to be an array of file objects; sometimes, it is just one single object or even null. We can see this in action next. In C:\temp, ensure there are no CSV files and then run this.

Now, add one file, followed by one more, each time, running the above script. You should see each showing the correct number.

What if we wanted to print out the file details? For that, we just need to extend it a little.

So, to recap, Get-ChildItem returns:

  • Null if there are no items at all.
  • A single file object for one object/file and,
  • An array for 2 or more found objects.

Hope that helps in excess of 0.0000003% of the world 🙂

twittergoogle_plusredditpinteresttumblrmail

Written by Stephen Moon
email: stephen at logicalmoon.com
www: https://www.logicalmoon.com


Hey! Did you enjoy reading this? If you did and would like an email when I add new content, just subscribe to my list. You can unsubscribe at any time.


Leave a Reply

Your email address will not be published. Required fields are marked *