Deleting All Files from a Folder Structure

by Nov 15, 2018

Sometimes tasks sound worse than they actually are. Let’s say you need to clear a folder structure and remove all files, leaving empty folders. Let’s further assume there are files on a whitelist that should not be deleted. With PowerShell, that’s easy to accomplish:

# Task:
# remove all files from a folder structure, but keep all folders,
# and keep all files on a whitelist

$Path = "c:\sample"
$WhiteList = "important.txt", "something.csv"

Get-ChildItem -Path $Path -File -Exclude $WhiteList -Recurse -Force | 
    # remove -WhatIf if you want to actually delete files
# ATTENTION: test thoroughly before doing this!
# you may want to add -Force to Remove-Item to forcefully remove files
    Remove-Item -WhatIf

Twitter This Tip! ReTweet this Tip!