PowerShell: Combine Results of Multiple Get-ChildItem Calls


You can use the Get-ChildItem cmdlet in PowerShell to retrieve all files and folders in a particular directory.

Occasionally you may want to use the Get-ChildItem cmdlet on several different directories and combine the results into a single variable.

You can use the following syntax to do so:

$my_files = @(Get-ChildItem "c:\users\bobbi\data1")
$my_files += @(Get-ChildItem "c:\users\bobbi\data2")

This particular example uses the Get-ChildItem cmdlet to first retrieve the items from the data1 folder.

Then, we use the Get-ChildItem cmdlet once more to retrieve the items from the data2 folder and use the += command to add these items to the items previously retrieved from the data1 folder.

Note that we also wrap each Get-ChildItem cmdlet with the @ symbol to force the output of each Get-ChildItem call to be an array, since the cmdlet will not return an array if only one file happens to be returned as the output.

The following example shows how to use this syntax in practice.

Example: How to Combine Results of Multiple Get-ChildItem Calls in PowerShell

Suppose that we would like to combine the items in the following two directories into a single variable:

  • c:\users\bobbi\data1
  • c:\users\bobbi\data2

We can use the following syntax to do so:

$my_files = @(Get-ChildItem "c:\users\bobbi\data1")
$my_files += @(Get-ChildItem "c:\users\bobbi\data2")

The following screenshot shows how to use this syntax in practice:

PowerShell combine results of multiple Get-ChildItem calls

Notice that the variable named $my_files now contains the items from both the data1 and data2 folders.

If we would like to know the total number of items stored in the $my_files variable then we could use the count property:

$my_files.count

The following screenshot shows how to use this syntax in practice:

The output tells us that there are 5 total items in the $my_files variable.

Note: You can find the complete documentation for the Get-ChildItem cmdlet in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Use Get-ChildItem with Filter
PowerShell: How to Use Get-ChildItem with Multiple Filters
PowerShell: How to Use Get-ChildItem to Get Full Path of Files
PowerShell: How to Use Get-ChildItem to Return Files Only

Leave a Reply