PowerShell: How to Save Folder Names in Directory to an Array


Often you may want to save the names of all folders in a particular directory to an array in PowerShell.

You can use the following syntax to do so:

$arr = Get-ChildItem c:\some\path -Directory | ForEach-Object {$_.Name}

This particular example saves all of the folder names in the directory that we specified to an array named $arr.

Here is what the various commands do:

  • Get-ChildItem: Retrieves all items from specific path
  • -Directory: Specifies that we only want to retrieve folders
  • ForEach-Object {$_.Name}: Returns only the name of the folder

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

Example: How to Save Folder Names PowerShell

Suppose that we would like to save all folders in the following location to an array:

  • c:\users\bobbi\dat

We can first use the Get-ChildItem cmdlet to view all files and folders in this directory:

We can see that this directory contains three folders:

  • athletes
  • coaches
  • managers

It also contains three files:

  • teams1.txt
  • teams2.txt
  • teams3.txt

Suppose that we would like to save only the folder names to an array.

We can use the following syntax to do so:

$arr = Get-ChildItem c:\users\bobbi\dat -Directory | ForEach-Object {$_.Name} 

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

PowerShell save folder names to array

Notice that when we output the values of $arr we can see that it only contains the names of the folders from the directory that we specified.

We can also use bracket notation to retrieve specific folders from the array.

For example, we can use the following syntax to retrieve the name of the first folder in the array:

$arr[0]

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

Notice that this returns athletes, which is the name of the first folder in the array.

Note: You can find the complete documentation for the ForEach-Object 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 to Get Full Path of Files
PowerShell: How to List Files in Directory by Date

Leave a Reply