Site icon SumTips

PowerShell: Recursively Delete All Files While Maintaining Directory Structure

Earlier today, after completing a backup operation, I was looking for a way to delete all the files from a directory and its subdirectories while keeping the directory structure intact. I wanted the directory structure to remain the same to prevent broken paths. As there were hundreds of files and folders, the quickest way to get this done would be to execute a script to automate the operation. The go-to tool for this was PowerShell, and as it turns out, it does the task rather simply and elegantly:

Recursively Delete All Files While Maintaining Directory Structure

The following command gets each file in $path and executes the delete method on each one.

Get-ChildItem –Path "C:\Backup" -Recurse -File | Remove-Item

In the end, the directory structure is left intact.

We can achieve the same result with Command Prompt by modifying “Delete All Files in a Directory Except Specified Ones” script we had seen earlier:

DEL . /S /Q

/S – is used to perform the delete operation recursively in sub folders
/Q – Quiet attribute is used to delete files with prompts
/F – Force attribute is used to delete read-only files

This would recursively delete all files in the current directory while leaving the folders intact.

That’s it. Hope this little code snippet was helpful in someway to you.

Exit mobile version