Reputation:
I am a long time viewer but this is my first question, so I apologize if I do it wrong.
I need to recursively delete all folders and files on a remote machine, and I want to prevent specific folders from getting deleted.
These excluded folders are listed in a text file called excludeDirectories.txt
, and there is one folder-name on each line.
My first attempt is a combination of command-prompt commands and the use of psexec
. The script is listed below. Note I am running these from a batch command, thus the double %%
:
net use r: \\machine\sharedFolderName
FOR /D %%a IN (R:\*.*) DO (
c:\pstools\psexec cmd /c rmdir /s /q R:\
)
This script deletes everything but I can't figure out how to check the text file for the current folder in the loop, and skip to the next folder in the FOR
loop, if the file is found in the text file.
I have spent days on this and have had trouble getting code to work that reads the folders into something I can use in an IF
statement and branching out of the psexec
line when a match is found.
Again, to beat a dead horse, what I am trying to accomplish is:
R:
driveFOR
loop to see if it is in the text fileFOR
loop is found in the text file, skip the line that deletes the folder and advance to the next folder in the FOR
loopUpvotes: 3
Views: 4845
Reputation: 105
Sorry, I did not notice you can't use powershell. But this answer could help those who reach this link.
You can do it better using PowerShell. I am using PowerShell 2.0.
Get-ChildItem -Path BASE_PATH_TO_SEARCH -Include FOLDER_TO_SEARCH -Recurse | ? { $_.FullName -inotmatch 'FOLDER_NAME_TO_EXCLUDE'} | Remove-Item -WhatIf -Recurse
Get-ChildItem : The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.
The good thing is that the Remove-Item cmdlet continues with the rest of the paths leaving those which throw errors.
One issue though is that running 'Get-Help Remove-Item -detailed' informs that '-Recurse' on 'Remove-Item' does not work properly. Well, for me this was alright. :-). No bad behaviour noticed.
I had used this to recursively delete bin folders from my VS solution base directory. That was a great relief. :-)
For details on Get-ChildItem read all the answers here: Excluding multiple folders when using Get-ChildItem
Upvotes: 0
Reputation: 55382
This assumes that the text file contains just the names, not the drive letter:
for /d %%a in (R:*) do findstr /i /x /c:"%%~nxa" excludeDirectories.txt || rd /s /q %%a
Upvotes: 1