Occasionally, it may become necessary to delete a set of subfolders within a given folder. Here is a simple chunk of code that deletes the folders from a list of folder names.

Warning: this code will delete the subfolders listed in $list without further confirmation. If the subfolders do not exit, nothing happens.

# the folder that contains the subfolders to remove
# (adjust to your needs)
$parentFolder = $env:userprofile

# list of folder names to remove (adjust to your needs)
$list = 'scratch', 'temp', 'cache'

# delete the folders found in the list
Get-ChildItem $parentFolder -Directory | 
  Where-Object name -in $list | 
  Remove-Item -Recurse -Force -Verbose

If you want to delete subfolders anywhere inside the parent folder, extend the search to recurse through subfolders by adding -Recurse to Get-ChildItem.

Below example deletes the subfolders in $list anywhere inside the folder structure of the parent folder.

Be aware that this may be risky because you are now finding subfolders inside of folders that you may not own and control which is why we added -WhatIf to Remove-Item: the code won’t actually delete the subfolders and just report what it would have done. Remove the parameter if you know what you are doing:

# the folder that contains the subfolders to remove
$parentFolder = $env:userprofile
# list of folder names to remove
$list = 'scratch', 'temp', 'cache'

# delete the folders found in the list
Get-ChildItem $parentFolder -Directory -Recurse | 
  Where-Object name -in $list | 
  Remove-Item -Recurse -Verbose -WhatIf

Twitter This Tip! ReTweet this Tip!

Anonymous