How to delete everything inside a notwork folder - batch-file

I would like to delete everything inside a folder on a network drive, but not the folder itself. It's school drive, therefore I can't delete the folder and replace it. If I try to delete the folder, it will look like i deleted it, until I restart my pc. I need to have access to the folder afterwards, and a restart in between is just too inconvenient.
Things I've tried:
cd \\LOCATION
rd . /q /s
However this error occurs
CMD does not support UNC paths as current directories.
I hope I explained this well enough, if there was something you didn't understand then just write, then I'll try to clarify.

Create a batch file and loop through every folder inside the folder you want to keep. Consider you have \\LOCATION\Folder\folder2 then folder3 etc. then this will remove all folders from within \\LOCATION\Folder but keep Folder:
set "myunc=\\LOCATION\Folder"
pushd "%myunc%" && (
for /d %%i in (*) do rmdir "%%i" /q /s
popd
)
Set sets a variable name of myfunc with a value which in this case is your path.
For /d is a loop that goes through each directory inside your %myunc% path and then simply do a rd on each.
Pushd allows you to pretty much cd to a network UNC path. pushd will create a temp drive letter for the UNC path. So it is almost like you doing net use X: \\servername\path
popd will then just remove the temp drive letter for you.
Open cmd.exe and type pushd /? and popd /?
To learn more on batch commands, from cmd.exe do help which will list all cmd commands, for each command you can run the /? switch to learn more about it.

Open the Start Menu and in the text box, type cmd.exe and hit Enter (or open the command prompt using your preferred method)
Switch to the network drive by typing Z: (where Z is the letter of the network drive)
Change to the parent directory of the directory you're trying to delete using cd path\to\parent\directory
Delete the directory using rmdir /S giantdir
For example, if you want to delete the directory O:\MG\WTF\BBQ\SOMANYFILES:
C:\Documents And Settings\Me> O:
O:> cd MG\WTF\BBQ
O:\MG\WTF\BBQ> rmdir /S SOMANYFILES
Or now that I think about it, I think you could just do
C:\Documents And Settings\Me> O:
O:> rmdir /S MG\WTF\BBQ\SOMANYFILES
but you would miss out on the chance to see Windows spell out OMGWTFBBQ in terminal font ;-)
By the way, rmdir (or del) does not move things to the Recycle Bin, it just deletes them, so be careful not to delete things you don't really want to.

Related

How to Mass Delete Files in Windows using batch

I recently refreshed my PC and upon finally finishing, I realized a pesky file named thumbs.db had been left in every folder and directory. I'm trying to find a simple way to DELETE ALL thumbs.db from my ENTIRE C: drive.
Code I've tried (Only removed thumbs.db from desktop)
dir thumbs.db /a /b /s
del thumbs.db /a /s
PS: I'm open to any Power Shell Ideas Also.
You can achieve this by running:
C:
cd /
del /s /q /f /a:h Thumbs.db
The first line sets the drive you want to run it on.
The second line points to the root directory of the drive.
The third line force deletes (/f) hidden (/a:h) thumbs.db without prompting (/q) in all subfolders (/s)

How to delete files matching a certain pattern in their name?

I'm creating a batch file that deletes all Rar$DIa0.??? folders in the %TEMP% directory.
Is this possible, and how to do it?
The ??? is three randomized numbers. And that's where I have trouble with - deleting all folders that have Rar$DIa0. in the name.
for /d is designed for just this type of use. Something like this should work (remove one of the % if you're testing from the command line):
for /d %%i in ("%TEMP%\Rar$DIa0.???") do rd "%TEMP%\%%i"
The /d makes it work on directory names instead of file names.
If you want to make it easier on yourself, change to the %TEMP% folder first:
pushdir
cd /d %TEMP%
for /d %%i in ("Rar$DIa0.???") do rd "%%i"
The ??? makes it only act on folders that have three letters after a .. If your folders don't have just a three letter extension, change .??? to .*. If you've got a typo, and there is no actual . in the foldername, just remove it and use Rar$DIa0??? or Rar$DIa0*
You may want to test it first by changing rd to echo to make sure you get the folders you want before actually deleting them.
For more information about for (pun intended) type for /? from a command prompt.
The command line to use in a batch file for this task is:
#for /D %%I in ("%TEMP%\Rar$DIa0.*") do #rd /Q /S "%%I"
Command FOR with option /D searches in folder defined by environment variable TEMP for subfolders with folder name starting with Rar$DIa0. not having hidden or system attribute set.
The loop variable I holds for each found subfolder matching this folder pattern the name of found folder with full path without double quotes although the path to temp folder very often contains 1 or more spaces.
For that reason just the command RD with the parameters /Q for quiet execution and /S for deleting also all subfolders in the specified folder must be called with referencing the current value of loop variable I enclosed in double quotes.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
for /?
rd /?
By the way: WinRAR deletes the temporary folders usually automatically, except a file is opened from within an archive for viewing/modifying it in another application and WinRAR is closed before the other application is exited with the opened file. In this case WinRAR can't delete the temporary folder with temporarily extracted file because the file is still opened in another application. Of course also command RD can't delete the temporary folder if this folder is still the current directory of another application or a file in this folder is still opened by another application with a read/write access lock.

DELTREE command windows 10 replacement [duplicate]

Say, there is a variable called %pathtofolder%, as it makes it clear it is a full path of a folder.
I want to delete every single file and subfolder in this directory, but not the directory itself.
But, there might be an error like 'this file/folder is already in use'... when that happens, it should just continue and skip that file/folder.
Is there some command for this?
rmdir is my all time favorite command for the job. It works for deleting huge files and folders with subfolders. A backup is not created, so make sure that you have copied your files safely before running this command.
RMDIR "FOLDERNAME" /S /Q
This silently removes the folder and all files and subfolders.
You can use this shell script to clean up the folder and files within C:\Temp source:
del /q "C:\Temp\*"
FOR /D %%p IN ("C:\Temp\*.*") DO rmdir "%%p" /s /q
Create a batch file (say, delete.bat) containing the above command. Go to the location where the delete.bat file is located and then run the command: delete.bat
The simplest solution I can think of is removing the whole directory with
RD /S /Q folderPath
Then creating this directory again:
MD folderPath
This will remove the folders and files and leave the folder behind.
pushd "%pathtofolder%" && (rd /s /q "%pathtofolder%" 2>nul & popd)
#ECHO OFF
SET THEDIR=path-to-folder
Echo Deleting all files from %THEDIR%
DEL "%THEDIR%\*" /F /Q /A
Echo Deleting all folders from %THEDIR%
FOR /F "eol=| delims=" %%I in ('dir "%THEDIR%\*" /AD /B 2^>nul') do rd /Q /S "%THEDIR%\%%I"
#ECHO Folder deleted.
EXIT
...deletes all files and folders underneath the given directory, but not the directory itself.
CD [Your_Folder]
RMDIR /S /Q .
You'll get an error message, tells you that the RMDIR command can't access the current folder, thus it can't delete it.
Update:
From this useful comment (thanks to Moritz Both), you may add && between, so RMDIR won't run if the CD command fails (e.g. mistyped directory name):
CD [Your_Folder] && RMDIR /S /Q .
From Windows Command-Line Reference:
/S: Deletes a directory tree (the specified directory and all its
subdirectories, including all files).
/Q: Specifies quiet mode. Does not prompt for confirmation when
deleting a directory tree. (Note that /q works only if /s is
specified.)
I use Powershell
Remove-Item c:\scripts\* -recurse
It will remove the contents of the folder, not the folder itself.
RD stands for REMOVE Directory.
/S : Delete all files and subfolders
in addition to the folder itself.
Use this to remove an entire folder tree.
/Q : Quiet - do not display YN confirmation
Example :
RD /S /Q C:/folder_path/here
Use Notepad to create a text document and copy/paste this:
rmdir /s/q "%temp%"
mkdir "%temp%"
Select Save As and file name:
delete_temp.bat
Save as type: All files and click the Save button.
It works on any kind of account (administrator or a standard user). Just run it!
I use a temporary variable in this example, but you can use any other! PS: For Windows OS only!
None of the answers as posted on 2018-06-01, with the exception of the single command line posted by foxidrive, really deletes all files and all folders/directories in %PathToFolder%. That's the reason for posting one more answer with a very simple single command line to delete all files and subfolders of a folder as well as a batch file with a more complex solution explaining why all other answers as posted on 2018-06-01 using DEL and FOR with RD failed to clean up a folder completely.
The simple single command line solution which of course can be also used in a batch file:
pushd "%PathToFolder%" 2>nul && ( rd /Q /S "%PathToFolder%" 2>nul & popd )
This command line contains three commands executed one after the other.
The first command PUSHD pushes current directory path on stack and next makes %PathToFolder% the current directory for running command process.
This works also for UNC paths by default because of command extensions are enabled by default and in this case PUSHD creates a temporary drive letter that points to that specified network resource and then changes the current drive and directory, using the newly defined drive letter.
PUSHD outputs following error message to handle STDERR if the specified directory does not exist at all:
The system cannot find the path specified.
This error message is suppressed by redirecting it with 2>nul to device NUL.
The next command RD is executed only if changing current directory for current command process to specified directory was successful, i.e. the specified directory exists at all.
The command RD with the options /Q and /S removes a directory quietly with all subdirectories even if the specified directory contains files or folders with hidden attribute or with read-only attribute set. The system attribute does never prevent deletion of a file or folder.
Not deleted are:
Folders used as the current directory for any running process. The entire folder tree to such a folder cannot be deleted if a folder is used as the current directory for any running process.
Files currently opened by any running process with file access permissions set on file open to prevent deletion of the file while opened by the running application/process. Such an opened file prevents also the deletion of entire folder tree to the opened file.
Files/folders on which the current user has not the required (NTFS) permissions to delete the file/folder which prevents also the deletion of the folder tree to this file/folder.
The first reason for not deleting a folder is used by this command line to delete all files and subfolders of the specified folder, but not the folder itself. The folder is made temporarily the current directory for running command process which prevents the deletion of the folder itself. Of course this results in output of an error message by command RD:
The process cannot access the file because it is being used by another process.
File is the wrong term here as in reality the folder is being used by another process, the current command process which executed command RD. Well, in reality a folder is for the file system a special file with file attribute directory which explains this error message. But I don't want to go too deep into file system management.
This error message, like all other error messages, which could occur because of the three reasons written above, is suppressed by redirecting it with 2>nul from handle STDERR to device NUL.
The third command, POPD, is executed independently of the exit value of command RD.
POPD pops the directory path pushed by PUSHD from the stack and changes the current directory for running the command process to this directory, i.e. restores the initial current directory. POPD deletes the temporary drive letter created by PUSHD in case of a UNC folder path.
Note: POPD can silently fail to restore the initial current directory in case of the initial current directory was a subdirectory of the directory to clean which does not exist anymore. In this special case %PathToFolder% remains the current directory. So it is advisable to run the command line above not from a subdirectory of %PathToFolder%.
One more interesting fact:
I tried the command line also using a UNC path by sharing local directory C:\Temp with share name Temp and using UNC path \\%COMPUTERNAME%\Temp\CleanTest assigned to environment variable PathToFolder on Windows 7. If the current directory on running the command line is a subdirectory of a shared local folder accessed using UNC path, i.e. C:\Temp\CleanTest\Subfolder1, Subfolder1 is deleted by RD, and next POPD fails silently in making C:\Temp\CleanTest\Subfolder1 again the current directory resulting in Z:\CleanTest remaining as the current directory for the running command process. So in this very, very special case the temporary drive letter remains until the current directory is changed for example with cd /D %SystemRoot% to a local directory really existing. Unfortunately POPD does not exit with a value greater 0 if it fails to restore the initial current directory making it impossible to detect this very special error condition using just the exit code of POPD. However, it can be supposed that nobody ever runs into this very special error case as UNC paths are usually not used for accessing local files and folders.
For understanding the used commands even better, open a command prompt window, execute there the following commands, and read the help displayed for each command very carefully.
pushd /?
popd /?
rd /?
Single line with multiple commands using Windows batch file explains the operators && and & used here.
Next let us look on the batch file solution using the command DEL to delete files in %PathToFolder% and FOR and RD to delete the subfolders in %PathToFolder%.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Clean the folder for temporary files if environment variable
rem PathToFolder is not defined already outside this batch file.
if not defined PathToFolder set "PathToFolder=%TEMP%"
rem Remove all double quotes from folder path.
set "PathToFolder=%PathToFolder:"=%"
rem Did the folder path consist only of double quotes?
if not defined PathToFolder goto EndCleanFolder
rem Remove a backslash at end of folder path.
if "%PathToFolder:~-1%" == "\" set "PathToFolder=%PathToFolder:~0,-1%"
rem Did the folder path consist only of a backslash (with one or more double quotes)?
if not defined PathToFolder goto EndCleanFolder
rem Delete all files in specified folder including files with hidden
rem or read-only attribute set, except the files currently opened by
rem a running process which prevents deletion of the file while being
rem opened by the application, or on which the current user has not
rem the required permissions to delete the file.
del /A /F /Q "%PathToFolder%\*" >nul 2>nul
rem Delete all subfolders in specified folder including those with hidden
rem attribute set recursive with all files and subfolders, except folders
rem being the current directory of any running process which prevents the
rem deletion of the folder and all folders above, folders containing a file
rem opened by the application which prevents deletion of the file and the
rem entire folder structure to this file, or on which the current user has
rem not the required permissions to delete a folder or file in folder tree
rem to delete.
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%\*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%\%%I" 2>nul
:EndCleanFolder
endlocal
The batch file first makes sure that environment variable PathToFolder is really defined with a folder path without double quotes and without a backslash at the end. The backslash at the end would not be a problem, but double quotes in a folder path could be problematic because of the value of PathToFolder is concatenated with other strings during batch file execution.
Important are the two lines:
del /A /F /Q "%PathToFolder%\*" >nul 2>nul
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%\*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%\%%I" 2>nul
The command DEL is used to delete all files in the specified directory.
The option /A is necessary to process really all files including files with the hidden attribute which DEL would ignore without using option /A.
The option /F is necessary to force deletion of files with the read-only attribute set.
The option /Q is necessary to run a quiet deletion of multiple files without prompting the user if multiple files should be really deleted.
>nul is necessary to redirect the output of the file names written to handle STDOUT to device NUL of which can't be deleted because of a file is currently opened or user has no permission to delete the file.
2>nul is necessary to redirect the error message output for each file which can't be deleted from handle STDERR to device NUL.
The commands FOR and RD are used to remove all subdirectories in specified directory. But for /D is not used because of FOR is ignoring in this case subdirectories with the hidden attribute set. For that reason for /F is used to run the following command line in a separate command process started in the background with %ComSpec% /c:
dir "%PathToFolder%\*" /AD /B 2>nul
DIR outputs in bare format because of /B the directory entries with attribute D, i.e. the names of all subdirectories in specified directory independent on other attributes like the hidden attribute without a path. 2>nul is used to redirect the error message output by DIR on no directory found from handle STDERR to device NUL.
The redirection operator > must be escaped with the caret character, ^, on the FOR command line to be interpreted as a literal character when the Windows command interpreter processes this command line before executing the command FOR which executes the embedded dir command line in a separate command process started in the background.
FOR processes the captured output written to handle STDOUT of a started command process which are the names of the subdirectories without path and never enclosed in double quotes.
FOR with option /F ignores empty lines which don't occur here as DIR with option /B does not output empty lines.
FOR would also ignore lines starting with a semicolon which is the default end of line character. A directory name can start with a semicolon. For that reason eol=| is used to define the vertical bar character as the end-of-line character which no directory or file can have in its name.
FOR would split up the line into substrings using space and horizontal tab as delimiters and would assign only the first space/tab delimited string to specified loop variable I. This splitting behavior is not wanted here because of a directory name can contain one or more spaces. Therefore delims= is used to define an empty list of delimiters to disable the line splitting behavior and get assigned to the loop variable, I, always the complete directory name.
Command FOR runs the command RD for each directory name without a path which is the reason why on the RD command line the folder path must be specified once again which is concatenated with the subfolder name.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
del /?
dir /?
echo /?
endlocal /?
for /?
goto /?
if /?
rd /?
rem /?
set /?
setlocal /?
To delete file:
del PATH_TO_FILE
To delete folder with all files in it:
rmdir /s /q PATH_TO_FOLDER
To delete all files from specific folder (not deleting folder itself) is a little bit complicated. del /s *.* cannot delete folders, but removes files from all subfolder. So two commands are needed:
del /q PATH_TO_FOLDER\*.*
for /d %i in (PATH_TO_FOLDER\*.*) do #rmdir /s /q "%i"
You can do it by using the following command to delete all contents and the parent folder itself:
RMDIR [/S] [/Q] [drive:]path
#ECHO OFF
rem next line removes all files in temp folder
DEL /A /F /Q /S "%temp%\*.*"
rem next line cleans up the folder's content
FOR /D %%p IN ("%temp%\*.*") DO RD "%%p" /S /Q
I tried several of these approaches, but none worked properly.
I found this two-step approach on the site Windows Command Line:
forfiles /P %pathtofolder% /M * /C "cmd /c if #isdir==FALSE del #file"
forfiles /P %pathtofolder% /M * /C "cmd /c if #isdir==TRUE rmdir /S /Q #file"
It worked exactly as I needed and as specified by the OP.
I had following solution that worked for me:
for /R /D %A in (*node_modules*) do rmdir "%A" /S /Q
It removes all node modules folder from current directory and its sub-folders.
This is similar to solutions posted above, but i am still posting this here, just in case someone finds it useful
Use:
del %pathtofolder%\*.* /s /f /q
This deletes all files and subfolders in %pathtofolder%, including read-only files, and does not prompt for confirmation.

Script that deletes itself by mistake

This batch script is supposed to map to PC and rename the files in that folder using the date & time stamp and copy them to another location on a different PC. It should then delete all the files in that source folder except for a file that called "LBBS.log". It all works fine except for the delete part. It isn't deleting anything in the folder and it is actually deleting the batch file itself. When I run it, it copies over fine but then it deletes itself. Can someone please tell me what I need to change for this to work. What am I missing? Its on a windows 7 environment. Thanks in advance.
net use x: \\MTLLBBS023\C$
set "stamp=%date:~4,2%%date:~7,2%%date:~10,4%%time:~0,2%%time:~3,2%%time:~6,2%"
set "source=MTLLBBS023"
xcopy /S /E /I x:\logs E:\Data\Logs\MTLLBBS023\%source%-%stamp%.*
cd x:\Logs
for %%i in (*) do if not %%i == LBBS.log del %%i
net use x: /delete
The problem is that your script and target directories are located on separate drives.
When you cd to another directory, the command will fail if you try to move to another drive without using the /d option.
Instead of cd x:\logs, you should say cd /d x:\logs - this will change the drive and directory.
Alternatively, instead of the net use and net use delete commands, you can simply pushd \\MTLLBBS023\C$ to go to the network drive (this also automatically creates a temporary network drive) and then popd at the end of the script to leave the directory and remove the mapped drive. This way, you don't need to cd at all.

directory is not empty error

I try in my batch file o delete folder(BR) with many files and subdirectories, I try the following:
if exist C:\BR (
rmdir "C:\BR" /S /q
)
but sometimes I get an error that a specific folder is not empty.these folder contains files of CSS.
what the problem??
rd /s /q DIRNAME
rmdir /s /q DIRNAME
The files that you can't delete are in use.
Close whatever program is holding them open, probably your browser, and try again.
Let me guess, your trying to delete your %TMP% folder.
EDIT: To answer zipi's question.
It will delete every file and folder that it can. So, if c:\tmp\dir2\dir3\open.txt is open, c:\tmp\emptyDir is an empty directory, and you do this:
c:\>dir c:\tmp /b /s
c:\tmp\a.txt
c:\tmp\dir2\b.txt
c:\tmp\dir2\dir3\open.txt
c:\>rd /q /s c:\tmp
c:\>dir /s /b c:\tmp
c:\tmp\dir2\dir3\open.txt
You will have deleted:
c:\tmp\a.txt
c:\tmp\dir2\b.txt
And removed:
c:\tmp\emptyDir
But still have the directories...
c:\tmp
c:\tmp\dir2
c:\tmp\dir2\dir3
...an the file:
c:\tmp\dir2\dir3\open.txt
If instead, a.txt was open, you'd only have:
c:\tmp\
and
c:\tmp\a.txt
On win7 I use a simple bat file to go around the problem:
call :rmdir "my_directory_01"
call :rmdir "my_directory_02"
pause
goto :EOF
:rmdir
if exist %1 rmdir /s /q %1
if exist %1 goto :rmdir
goto :EOF
I had a similar problem. Tried lots of different solutions, but ultimately only the following worked:
rmdir c:\<directory> /s /q
Previously using other methods in CMD I was getting the following:
The directory is not empty.
I had the same issue and the solution is very silly. Please use /Q first and the /S to resolve your issue. so command should be something like:
IF EXIST %build_folder% RD /Q /S %build_folder%
Please let me know if this solves your issue.
Regards
Anuj
To remove directory in command line, you have to remove all of files and subsolders it cointainst at the first place. The problem may occur if some of those items are read-only. /f will try to force delete them.
Try
if exists C:\BR (del "C:\BR" /f /s /q)
Here you have MS docs of the DEL command: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/del.mspx?mfr=true
This worked for me
you will need to go to any drive where the folder is. Then right click on drive > properties > Check Scan disk or scan drive and for windows8 scan and repair
then go back to your folder and delete it
Batch - Getting "The directory is not empty" on rmdir command
In my case the failure to remove a directory using rd /Q /S and getting Directory not empty was down to file permissions. The batch job was doing a backup and removing oldest backup folder at the end to keep latest 10 backups. The normal user account only had read and execute permission on certain files in the sub folders. Running the batch file containing the rd commands under Task Scheduler with a tick in the option "run with highest privileges" enabled directory's to be removed.
You could achieve something similar as a one off if you run your batch file under cmd and choose run as administrator. In Windows 7 type CMD in the Search programs and files box, then right click on cmd.exe at the top of the popup window and click Run as Administrator. Then find and run your batch file in the cmd "black background" window.

Resources