- 🧹 Removing files like Thumbs.db with PowerShell makes development folders much cleaner.
- ⚙️
Get-ChildItemandRemove-Itemdelete files automatically, even in folders with many subfolders. - 🛡️ Using
-WhatIfandTry-Catchstops you from accidentally deleting files when you run scripts. - 📄 Keeping a log of deleted files with
Tee-Objecthelps you check what was deleted and undo changes if needed. - 🔐 To delete read-only and hidden files, you need to use
-Forceand run PowerShell as an administrator.
PowerShell is an important tool for system administrators and developers who want to manage files automatically and quickly. You can use it to remove files that take up too much space, like Thumbs.db. Also, you can delete .log files in a CI/CD build or clear subfolders before an application runs. PowerShell gives you strong commands you can script. This guide shows you how to use PowerShell to delete files in subfolders, use filters and safety checks, deal with unusual situations, and add cleanup steps to your daily work. This makes sure things are done the same way every time.
Real-World Use Cases for Deleting Files Recursively
Deleting files in subfolders with PowerShell helps with many common situations in development and IT work:
🔄 Deleting Thumbs.db Across Code Repositories
Windows automatically makes Thumbs.db files in folders that have pictures. These files can make Git repositories messy and cause problems when you push or pull code. Most development setups do not need these files. You should delete them and keep them out of source control.
PowerShell helps clean these up automatically. It looks through all folders in a project and deletes every Thumbs.db file.
🧪 Cleaning Up Log and Temp Files
Automated tests and monitoring tools often make .log, .tmp, or .bak files. These files can build up over time and use disk space. They can also confuse people looking at output folders. Deleting these files in subfolders after each test run makes things clear again.
🧰 Resetting Project Folders Between Builds
For CI/CD workflows, temporary folders or cache folders must be cleared between builds. Deleting them by hand often leads to mistakes and takes a long time. But with a few lines in PowerShell, you can make sure your build or test setups start new each time.
📸 Wiping Auto-Generated Artifacts
Some applications make extra files, like debug screenshots, PDF exports, or trace files. These can be helpful for a short time. But you should delete them often to keep your work area tidy.
File cleanups in subfolders with PowerShell make this easy. You can do it again and again, and you can script it.
Understanding PowerShell’s Key Cmdlets
Deleting files in subfolders with PowerShell mostly uses two main commands:
🔍 Get-ChildItem
This command finds files and folders. It can look inside subfolders using the -Recurse switch. With filters, you can find files by their type, name, or path. Get-ChildItem works like shell commands such as ls or dir, but it is much stronger.
Command options:
Get-ChildItem -Path "C:\Logs" -Recurse -Filter "*.log"
🧹 Remove-Item
This command is used to delete things. It can delete files, folders, registry keys, and more. Be careful when you use it. Deleting items happens right away, and you usually cannot get them back.
Here's how they combine:
Get-ChildItem -Path "C:\MySite" -Recurse -Filter "Thumbs.db" | Remove-Item
This finds and deletes every "Thumbs.db" file under the specified path and its subfolders.
Basic Script: Delete Specific Files from All Subfolders
To delete specific files like Thumbs.db from all subfolders within a main path, use this simple script:
Get-ChildItem -Path "C:\MyProject" -Recurse -Filter "Thumbs.db" | Remove-Item
Breakdown:
-Path: The main folder to start looking in.-Recurse: Tells PowerShell to look inside all subfolders.-Filter: Finds a certain type of file or file name.Remove-Item: Deletes all files that match.
This script quickly deals with extra files in folders with many subfolders. You can also easily change it to find different file names.
Adding Safety Checks with -WhatIf
PowerShell helps you avoid accidentally deleting files with the -WhatIf flag. This feature shows what would be deleted without actually deleting anything:
Get-ChildItem -Path "C:\MyProject" -Recurse -Filter "Thumbs.db" | Remove-Item -WhatIf
This helps with:
- Making sure you are deleting the right files.
- Checking for files you did not mean to delete.
- Work for teams where many developers use the same folders.
Use -WhatIf often when you test new or broad patterns like *.*.
Advanced Filtering with Where-Object
You can add conditions to your file searches using Where-Object. For example, you can delete only smaller Thumbs.db files:
Get-ChildItem -Path "C:\MyProject" -Recurse | Where-Object {
$_.Name -eq "Thumbs.db" -and $_.Length -lt 10000
} | Remove-Item
Benefits:
- Stops the deletion of very large or odd files.
- Lets you delete only from certain folders.
- Allows for complex script rules, good for complicated file systems.
Another example with folder path filtering:
Get-ChildItem -Path "C:\MyProject" -Recurse | Where-Object {
$_.DirectoryName -like "*Screenshots*" -and $_.Name -eq "Thumbs.db"
} | Remove-Item
Find files even more exactly by folder name or pattern.
Handling Hidden or Read-Only Files
Thumbs.db and other system files are often marked as Hidden or ReadOnly. If you do not handle them in a special way, they cannot be deleted easily.
Use -Force to Bypass Attributes:
Get-ChildItem -Recurse -Filter "Thumbs.db" | Remove-Item -Force
Additional Tips:
- Run PowerShell as Administrator to get to the files.
- If you still cannot delete files, check their properties or use
Takeownto change who owns them.
👉 According to Microsoft Docs, -Force is needed for hidden or system files (Microsoft Docs, 2023b).
Batch Logging of Deleted Files
You may want to keep a list of files deleted during cleanup. PowerShell lets you do this simply with Tee-Object.
Get-ChildItem -Recurse -Filter "Thumbs.db" | Tee-Object -FilePath "deleted_files.log" | Remove-Item
What happens here:
Tee-Objectputs the list of files to be deleted intodeleted_files.log.- Then, the list goes through the pipeline and
Remove-Itemdeletes the actual files.
Use log files to:
- Keep a record of what happened.
- Show how automation worked for teams or for rules.
- Find problems with files that were missed or did not follow rules.
Error Handling and Robust Scripting
To make your scripts stronger, use error handling with a Try-Catch block. This stops them from crashing when files are locked or protected:
Try {
Remove-Item "C:\Assets\Thumbs.db" -ErrorAction Stop
} Catch {
Write-Host "Could not delete: $_"
}
Use this with -ErrorAction Stop to make the Catch block run right after a problem happens.
Advanced usage—wrap this into a loop:
$files = Get-ChildItem -Recurse -Filter "Thumbs.db"
foreach ($file in $files) {
Try {
Remove-Item $file.FullName -Force -ErrorAction Stop
} Catch {
Write-Warning "Skipped file: $($file.FullName) - $_"
}
}
This lets you fully control what happens if a single file fails to delete. This is very important in team settings or for scripts that run in production.
Making It Reusable: Turn It Into a PowerShell Function
Change your script into a PowerShell function that you can use again. This makes your code tidier and lets you do it many times.
Function Remove-SpecificFiles {
param(
[Parameter(Mandatory = $true)][string]$RootPath,
[Parameter(Mandatory = $true)][string]$FileName
)
Get-ChildItem -Path $RootPath -Recurse -Filter $FileName | Remove-Item -Force
}
Call it from any file or session like this:
Remove-SpecificFiles -RootPath "C:\Workspace" -FileName "Thumbs.db"
Save functions like this in your profile or a reusable .ps1 helper script.
Running Scripts Safely in Team Environments
Use these good ways to work to keep deletion scripts safe in shared or large company settings:
- 🔏 Script Signing: Sign scripts with trusted certificates to make sure no one has changed them.
- 🚫 Avoid Overmatching: Never filter with
*.*unless you’re absolutely sure of what it includes. - 🔐 Execution Policies: Use certain policies like
RemoteSignedon workstations. - 🔁 Scripting Reviews: Have others review file deletion scripts. This is extra important if they are used automatically.
More guidelines can be found on the TechNet Forums.
Integrating into CI/CD Pipelines
CI/CD systems get a lot of good from scripted file cleanups:
How to Integrate:
- 🧪 Pre-build Tasks: Delete old files before builds with scripts.
- ⚙️ Pipeline Steps: Add PowerShell cleanup as part of GitHub Actions, GitLab CI, or Azure DevOps pipelines.
- 🧰 Build Caching Cleanup: Stop bad build files by cleaning certain folders each time.
Example in GitHub Actions:
- name: Clean Thumbs.db files
run: |
pwsh -Command "Get-ChildItem -Recurse -Filter 'Thumbs.db' | Remove-Item -Force"
This helps make clean, predictable builds and cuts down on bugs from leftover files.
When Not to Use Recursive Deletes
Deleting files in subfolders is strong, but dangerous if used wrong:
Avoid if:
- Folders contain files that are not fully managed or are shared.
- File patterns could accidentally find user-made content.
Alternatives:
- Use
.gitignoreto stop adding problem files to source control. - Turn on group policies to stop
Thumbs.dbfiles from being made at all. - Teach teams to often leave out unneeded operating system files.
Always double-check with -WhatIf before deleting files in subfolders from large or important projects.
Other Useful PowerShell File Commands for Developers
While working with files, you may find these commands useful:
- ❌
Remove-Item: Deletes the files or folders you want to delete. - 🚚
Move-Item: Useful for archiving instead of deleting. - 🔄
Copy-Item: Backup files before deletions that might cause problems. - 🔍
Test-Path: Check if a file exists before doing something. - 🗒️
Clear-Content: Erase file contents without deleting files.
Combining these across scripts gives you full control over your local or shared file system.
Clean Dev Folders, Clean Minds
PowerShell's good commands change how you manage files. They help make things less messy and do boring devops tasks automatically. With deleting files in subfolders using Get-ChildItem and Remove-Item, safety checks like -WhatIf, and filter rules through Where-Object, you can safely, but strongly, remove files from subfolders like Thumbs.db. Put these scripts into functions, add them to CI/CD, and log your deletions for a good mix of doing things automatically and being careful.
Start small. Use dry runs. Add your favorite cleanup scripts to your tools, and enjoy cleaner projects with every run.
Citations
- Microsoft Docs. (2023). Get-ChildItem (Microsoft.PowerShell.Management). Retrieved from https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem
- Microsoft Docs. (2023). Remove-Item (Microsoft.PowerShell.Management). Retrieved from https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/remove-item
- TechNet Forums. (2021). Best Practices for File Deletion with PowerShell. Retrieved from https://social.technet.microsoft.com