Using Get-ChildItem Results in PowerShell

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

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:

1
2
$files = Get-Child-Item -Filter *.csv -Path C:\temp
$files.Count

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:\ytemp, ensure there are no CSV files and then run this.

1
2
$filesFound = Get-ChildItem -Filter *.csv -Path C:\temp
Write-Host "Number of files:" $(If ($filesFound -is [array]) { $filesFound.Count } Else { if (-Not $filesFound) { 0 } else { 1 }})

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function PrintFileDetails ($fileDetails)
{
Write-Host "File:" $fileDetails.FullName
Write-Host "Name:" $fileDetails.Name
Write-Host "Extension:" $fileDetails.Extension
}

$filesFound = Get-ChildItem -Filter *.csv -Path C:\temp

# Counting number of files in collection
Write-Host "Number of files:" $(If ($filesFound -is [array]) { $filesFound.Count } Else { if (-Not $filesFound) { 0 } else { 1 }})
Write-Host

# Taking the first item
if ($filesFound -is [array]) {
PrintFileDetails $filesFound[0]
}
elseif ($filesFound) {
PrintFileDetails $filesFound
}
else {
Write-Host "No files"
}

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 :-)


Hi! Did you find this useful or interesting? I have an email list coming soon, but in the meantime, if you ready anything you fancy chatting about, I would love to hear from you. You can contact me here or at stephen ‘at’ logicalmoon.com