PowerShell Foreach File in Folder

Do you want to iterate files in a folder using PowerShell? In this PowerShell tutorial, I will explain everything about the PowerShell Foreach file in a folder.

To iterate through each file in a folder using PowerShell, you can use the Get-ChildItem cmdlet to retrieve the files and then loop through them with a foreach statement. Here’s a concise example:

$files = Get-ChildItem -Path "C:\MyFolder"
foreach ($file in $files) {
    # Your code to process each file
}

This script will loop through each file in “C:\MyFolder”, allowing you to execute your desired actions on each file within the loop.

PowerShell Foreach File in Folder

The foreach statement in PowerShell is used to execute a set of commands for each item in a collection. In the context of files, the collection will be a list of files that you retrieve using the Get-ChildItem cmdlet.

Iterate Through Files in a Folder Using Basic Foreach Loop

Here’s a simple example using foreach to loop through each file in a directory:

$files = Get-ChildItem -Path "C:\MyFolder"
foreach ($file in $files) {
    # Perform actions on each file
    Write-Output $file.FullName
}

In this script, Get-ChildItem retrieves all items in “C:\MyFolder”, and the foreach loop iterates over each item, outputting its full name.

You can see the output in the screenshot below:

PowerShell Foreach File in Folder

Recursively Looping Through Files

To include subdirectories in your search and process files within them, use the -Recurse parameter:

$files = Get-ChildItem -Path "C:\MyFolder" -Recurse
foreach ($file in $files) {
    # Perform actions on each file
    Write-Output $file.FullName
}

This will list all files in “C:\MyFolder” and its subfolders.

Filtering Specific File Types

If you’re only interested in specific file types, use the -Filter parameter to narrow down the results:

$files = Get-ChildItem -Path "C:\MyFolder" -Filter "*.txt"
foreach ($file in $files) {
    # Perform actions on each .txt file
    Write-Output $file.FullName
}

This example will process only .txt files in “C:\MyFolder”.

Using the Pipeline with Foreach-Object

An alternative to the foreach statement is the Foreach-Object cmdlet, which can be used in conjunction with the pipeline:

Get-ChildItem -Path "C:\MyFolder" | Foreach-Object {
    # Perform actions on each file
    Write-Output $_.FullName
}

Here, $_ represents the current object in the pipeline, which is each file as it’s passed down from Get-ChildItem.

PowerShell Foreach File in Folder – Examples

Now, let us check out a few examples of what you can do by looping through files using the foreach loop.

Renaming Files

To rename files in a directory, you could use the Rename-Item cmdlet within your loop:

$files = Get-ChildItem -Path "C:\MyFolder" -Filter "*.log"
foreach ($file in $files) {
    $newName = "Processed_" + $file.Name
    Rename-Item $file.FullName -NewName $newName
}

This script prepends “Processed_” to the name of each .log file.

Moving Files

Moving files to a new directory can be done with the Move-Item cmdlet:

$files = Get-ChildItem -Path "C:\MyFolder" -Filter "*.docx"
foreach ($file in $files) {
    $destinationPath = "C:\ProcessedFiles\" + $file.Name
    Move-Item $file.FullName -Destination $destinationPath
}

Each .docx file from “C:\MyFolder” is moved to “C:\ProcessedFiles”.

Modifying File Content

To modify the content of each file, you might use Get-Content and Set-Content:

$files = Get-ChildItem -Path "C:\MyFolder" -Filter "*.config"
foreach ($file in $files) {
    $content = Get-Content $file.FullName
    $newContent = $content -replace "oldvalue", "newvalue"
    Set-Content -Path $file.FullName -Value $newContent
}

This script replaces “oldvalue” with “newvalue” in each .config file’s content.

Error Handling in PowerShell ForEach Loop

When automating file processing, it’s essential to include error handling to deal with unexpected issues. Here’s how you can incorporate basic error handling in your foreach loop:

$files = Get-ChildItem -Path "C:\MyFolder" -ErrorAction SilentlyContinue
foreach ($file in $files) {
    try {
        # Try to perform actions on each file
        Write-Output $file.FullName
    } catch {
        Write-Error "An error occurred processing file: $($file.FullName)"
    }
}

The -ErrorAction SilentlyContinue parameter tells Get-ChildItem to ignore non-terminating errors, while the try/catch block handles any terminating errors during processing.

Conclusion

Whether you’re renaming, moving, or modifying files, the PowerShell foreach loop, along with cmdlets like Get-ChildItem, Rename-Item, Move-Item, and Set-Content are available.

In this PowerShell tutorial, I have explained how to use the foreach loop to iterate through files in a folder.

You may also like: