Get-ChildItem in PowerShell

One of the Cmdlets on PowerShell is Get-ChildItem. This command is used to get the items and child items in one or more specified locations. It provides functionality similar to dir command in Windows’ command.

Most of the time, Get-ChildItem will return a list of items that you want to collect, for example, a list of files in a specific folder, etc. When you have a list, usually you want to know how many items are in the list. In PowerShell, this can be achieved by accessing the Count property of the list.

For example, if we want to get the list of files in D:\data folder, we use command:

$list = Get-ChildItem "D:\Data"

The list variable now contains the list of files inside the D:\Data folder. If you want to know how many files are inside that folder, you can use command:

Write-Host $list.Count

One that often creates confusion is when the D:\Data folder contains only one file. In this case, the Get-ChildItem will return only one value (System.IO.FileInfo object), which is a scalar value that does not have Count property. An attempt to access the Count property will return nothing. The Get-ChildItem only returns an array if it detects more than one item.

If you have a script that will do something on this folder if the folder contains one or more items, your script will fail if the folder contains only one item.

To avoid this mistake, we can force PowerShell to always return an array. To do this, we need to enclose the command with the array notation @(). So the command to get the list now becomes:

$list = @(Get-ChildItem "D:\Data")

Now you can always use the Count property to get how many files are inside that folder.

Post a Comment

Leave your comment below
The comment is moderated. Only comments related to the post will be accepted.
Your name
Email address
Your comment

Read Comments No comment yet Comment feed

You can get this information from:
Close this window
Email This Information
To send the message, please fill the form below
Email To
Your Email

Please enter the text on the following image in the verification box below. Click here if you cannot read the text. All alphabets are in upper case.

Verification image