PowerShell: Delete folders based on name
Use this simple script to delete any folders in a directory (or its subdirectories) that contain a particular string or strings.
I have a lot of folders which contain legacy FrontPage extensions (in the format “_vti_cnf”). These are of no use and are simply taking up space on my hard drive.
Whilst I could trawl through every directory and subdirectory and manually delete each and every instance of a _vti_cnf folder or file, this process is much faster when PowerShell is employed. The following script will delete folder (as well as subfolders and files) based on a string or a series of strings. In this example, it will delete any folder or file that contains “_vti_cnf” or “.svn”.
$source="C:\path\to\files" #location of directory to search
$strings=@("*vti_cnf", "*.svn")
cd ($source); get-childitem -Include ($strings) -Recurse -force | Remove-Item -Force –Recurse
There are just two parameters that need to be specified:
$source
= The folder in which to start the search$strings
= The search strings that will be used to decide if folders should be deleted
As with all scripts of this nature, caution must be employed. Always run the script with a -whatif
command first to see what will happen when the script is run.
Comments
3 responses to “PowerShell: Delete folders based on name”
I tested your script to remove duplicate directories in all sub directories under the source and it worked for the first sub directory but did not search subsequent sub directories also under the source.
It returned this error:
Get-ChildItem : Access is denied
At H:\Batch Remove TEST\cm.ps1:1 char:1
+ Get-ChildItem . -Include 1306001,1311001 -Recurse -Force | Remove-Ite …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-ChildItem], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetChildItemCommand
I have hundreds of duplicate named sub directories in multiple sub directories under one directory I need to delete the specific directories and their contents and going through each of them by hand is very time consuming.
I have a list of directory names I need to delete.
Source dir
-sub dir 1
-sub dir
-sub dir 2
-sub dir
I have hundreds of duplicate directory names to process so it would be great if it could reference a text file I could type up that might have them listed one line at a time. (or whatever you suggest)
I would even be willing to pay you for your time.
Win 10 pro, latest powershell.
Thank You!
To Curtis Walter –
The error you get is just because you don’t have permissions on the folders you are trying to delete.
Did you run powershell with Admin rights?
Thanks a lot, awesome!!
Works perfect!!!
To Curtis Walter – That message is because you don’t have permissions over the directory. Did you run powershell with Admin rights?