How to Loop Through Folders in PowerShell (With Example)


Often you may want to use PowerShell to loop through all folders in a directory and perform some task.

You can use the following basic syntax to do so:

Get-ChildItem -Recurse -Directory | ForEach-Object {
    New-Item -ItemType file -Path "$($_.FullName)" -Name "new_data.txt"
}

This particular example loops through each folder in the current directory, including all subfolders, and creates a new file named new_data.txt in each folder.

Note that we use Get-ChildItem -Recurse -Directory to recursively retrieve each folder in the current directory.

We then use the ForEach-Object cmdlet to perform some action in each folder.

Feel free to use any code that you’d like in the ForEach-Object to perform whatever specific task you would like in each folder.

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

Example: How to Loop Through Folders in PowerShell

We can use the following syntax with the Get-ChildItem cmdlet to first view all folders and subfolders in the current directory:

Get-ChildItem -Recurse -Directory

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

We can see that the current directory has the following folders:

  • east-data
  • north-data
  • south-data
  • west-data

None of these folders have any subfolders.

Suppose that we would like to loop through each of these four folders and insert a new text file named new_data.txt.

We can use the following syntax to do so:

Get-ChildItem -Recurse -Directory | ForEach-Object {
    New-Item -ItemType file -Path "$($_.FullName)" -Name "new_data.txt"
}

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

PowerShell loop through folders

We can use the Get-ChildItem cmdlet once again to view the updated contents of the folders.

For example, we can use the following syntax to view the contents in the folder named east-data:

Get-ChildItem east-data

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

We can see that this folder contains a new file named new_data.txt.

If we use the Get-ChildItem cmdlet to view the contents of each folder, we will find that each folder contains a text file named new_data.txt.

Feel free to use similar syntax to loop through each folder in your own directory and perform some specific action.

Related Tutorials

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

PowerShell: How to Loop Through Each Line of CSV File
PowerShell: How to Run a Loop X Number of Times
PowerShell: How to Delete All Files with Specific Extension
PowerShell: How to Rename File Extension of Multiple Files

Leave a Reply