I am trying to write a simple tool to delete junk Mac files from a Windows system, however, I am having trouble as a specified folder (.fseventsd) remains, no mater what I do. Below is the batch file, and the specific area of concern is the rmdir command in the :.fseventsd section.
rem #echo off
cls
cd \
:.fseventsd
echo Searching for '.fseventsd' folders.
rmdir /S /Q ".fseventsd" 2> nul
if errorlevel 1 echo No '.fseventsd' folders were found.
goto :.DS_STORE
if errorlevel 0 echo All '.fseventsd' folders have been deleted.
:.DS_STORE
echo.
echo Searching for '.DS_STORE' files.
del /s /q /f /a:rash .DS_STORE 2> nul
if errorlevel 1 echo No '.DS_STORE' files were found.
goto ._.*
if errorlevel 0 echo All '.DS_STORE' files have been deleted.
:._.*
echo.
echo Searching for '._.*' files.
del /s /q /f /a:rash ._.* 2> nul
if errorlevel 1 echo No '._.*' files were found.
goto END
if errorlevel 0 echo All '._.*' files have been deleted.
echo.
:END
echo All tasks have now been finished.
pause
Any help would be greatly appreciated.
You need to use a for /r loop which loops through subfolders just like this:
for /R "C:\path\you\want" %%A IN (.) do (
if "%%A"=="Foldernameyouwant" rd Foldernameyouwant
You can make any minor changes you want to the code provided.
Hope this helps!
Related
I have this batch file which is supposed to find and delete specific files if found, but it keeps returning and displaying errors when the files are not found.
I had deleted the /S switch from the DELETE command to make the found files silent.
The code is below:
For /F "delims=" %%A in (
'Dir /B/S "*,*" ^| findstr ",[0-9][0-9]*$" '
) Do Del "%%A"
DEL /Q *.bak
ECHO bak files deleted
DEL /Q *.prjpcb.zip
ECHO Project History Zips deleted
DEL /Q *.pcbdoc.zip
ECHO PCB History Zips deleted
DEL /Q *.SchDoc.zip
ECHO Schematic History Zips deleted
DEL /Q *.PcbLib.zip
ECHO PCB Library History Zips deleted
DEL /Q *.SchLib.zip
ECHO Schematic Library History Zips deleted
DEL /Q *.OutJob.zip
ECHO Output Jobs History Zips deleted
ECHO on
TIMEOUT 5
How do I get the file to display only the echo when it deletes the files and nothing if nothing is found?
You can redirect the output to nul, if you really just never want to see any information from a command:
del /q *.bak >nul 2>&1
>nul redirects standard output, and 2>&1 redirects error output to the same place as standard output. Note that >nul can be written as 1>nul because it's the "first" output stream (standard).
Further note that nul represents a special case for the 2 output streams, such that you can do this:
del /q *.bak >nul 2>nul
https://ss64.com/nt/syntax-redirection.html
I am trying to get this script to backup a specific folder/files and zip them, then move the zip to a diff folder.
but i keep getting an error.
#ECHO off
SETLOCAL
ECHO + Setting up environment variables.
SET BACKPATH=%ThisService_RootDirectory%temp\
SET ARCPATH=C:\Program Files\7-Zip\7z.exe
SET ARCPARAMS=a -y
SET DAYSTOKEEP=3
SET ARCHIVE_DAYSTOKEEP=30
SET SOURCEPATH=%ThisService_RootDirectory%MPMissions
SET DEST_PATH=%ThisService_RootDirectory%Backups
SET BACKUP_DEST=%date:~-7,2%-%date:~4,2%-%date:~-4,4%
IF NOT EXIST "%BACKPATH%" (
ECHO ! Backup Path not found, exiting.
GOTO END
) ELSE (
ECHO * Backup Path Found.
)
IF NOT EXIST "%ARCPATH%" (
ECHO ! Archiver not found, exiting.
GOTO END
) ELSE (
ECHO * Archiver Found.
)
ECHO * Copying Files...
xcopy "%SOURCEPATH%\Documents" "%BACKPATH%\%BACKUP_DEST%\MPMissions" /v /e /s /i /y 1>NUL 2>NUL
ECHO * Archiving files...
CD /D "%BACKPATH%"
FOR /f %%a IN ('FORFILES /P %BACKPATH% /C "cmd /c if #isdir==TRUE echo #file" /D -%DAYSTOKEEP%') DO (
IF NOT EXIST %%a.7z (
"%ARCPATH%" %ARCPARAMS% %%a.7z %BACKPATH%\%%a\*.* 1>NUL 2>NUL
copy %%a.7z %DEST_PATH% 1>NUL 2>NUL
del %%a.7z 1>NUL 2>NUL
)
)
ECHO * Cleaning folders older than %DAYSTOKEEP% days..
FORFILES /P %BACKPATH% /C "cmd /c if #isdir==TRUE rmdir /s /q #file" /D -%DAYSTOKEEP% 1>NUL 2>NUL
ECHO * Cleaning files older than %DAYSTOKEEP% days..
FORFILES /P %BACKPATH% /M *.7z /C "cmd /c if #isdir==FALSE del #file" /D -%DAYSTOKEEP% 1>NUL 2>NUL
ECHO * Cleaning archives files older than %ARCHIVE_DAYSTOKEEP% days..
FORFILES /P %DEST_PATH% /M *.7z /C "cmd /c if #isdir==FALSE del #file" /D -%ARCHIVE_DAYSTOKEEP% 1>NUL 2>NUL
:END
ENDLOCAL
once I run the script it gives this message:
Setting up environment variables.
Backup Path Found.
Archiver Found.
Copying Files...
Archiving files...
ERROR: No files found with the specified search criteria.
Cleaning folders older than 3 days..
Cleaning files older than 3 days..
Cleaning archives files older than 30 days..
The script has executed successfully. You may close this window.
Now the variable %ThisService_RootDirectory% is part of tcadmin which is a gaming server service, so that variable where im executing the batch script would turn that variable into an actual path of the users service
example:
%ThisService_RootDirectory%
is
C:\TCAFiles\users\admin\5\
the script copies the files to the required folder, but it does not seem to zip the files and move the zip to the required folder.
can anyone give some assistance here please.
original source is at https://community.spiceworks.com/topic/482860-batch-script-to-transfer-and-compress
It's not a direct response to your question but why reinvent the wheel ?
All you need is in 7zBackup.ps1 (a powershell script which does exactly this)
I have a directory which has subdirectories like this:
C:\FILES
C:\FILES\DONE
I want to check that FILES contains no files:
if not exist C:\FILES\*.* (
echo No files to process.
exit /b
)
But the test "not exist ..." is never true because of the subdirectory.
Any ideas on how to check if the directory has any files that are not directories?
Try to get the list of files and if it fails, there are no files
dir /a-d "c:\files\*" >nul 2>nul || (
echo No files to process
exit /b
)
If there are no files, the dir /a-d command (the switch means exclude directories) will fail. || is a conditional execution operator that will execute the following commands if the previous one has failed.
Only when there are files, the for execute the goto.
for %%a in (C:\FILES\*.*) do goto files
echo No files to process.
exit /b
Simple code:
for /f "delims=|" %%f in ('dir /b c:\FILES\') do goto :files
echo No files found
pause
goto:eof
:files
echo Files found
pause
goto:eof
If you want to check if exists sub-directories on this level:
(DIR /D "C:\FILES\" | findstr /i /p /r /c:"2 Directory" > nul 2> nul) && echo "No directories except current and parent."
This simple inline command could be easy adapted for any situation ;-)
Try
if not exist dir c:\FILES\*.* /a:-d (
You can find more on dir here
PS
I do not have DOS at my reach. So I can't test the above code snippet. But I think it is close to what you are looking for.If not something very close to that should work.
I need to delete all empty folders from my application folder using windows command prompt?
How can I create a bat file like that?
Please help me.
You can use the ROBOCOPY command. It is very simple and can also be used to delete empty folders inside large hierarchy.
ROBOCOPY folder1 folder1 /S /MOVE
Here both source and destination are folder1, as you only need to delete empty folders, instead of moving other(required) files to different folder. /S option is to skip copying(moving - in the above case) empty folders. It is also faster as the files are moved inside the same drive.
A simpler way is to do xcopy to make a copy of the entire directory structure using /s switch. help for /s says Copies directories and subdirectories except empty ones.
xcopy dirA dirB /S
where dirA is source with Empty folders. DirB will be the copy without empty folders
for /f "usebackq" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"
from: http://blogs.msdn.com/b/oldnewthing/archive/2008/04/17/8399914.aspx
Of course I'd test it first without deleting before I do that command. Also, here's a modded version from the comments that includes folders with spaces:
for /f "usebackq delims=" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"
P.S. there are more comments in the blog post that might help you out so be sure to read those too before you try this out
You don't need usebackq:
FOR /F delims^= %%A IN ('DIR/AD/B/S^|SORT/R') DO RD "%%A"
Adding to corroded answer from the same referenced page is a PowerShell version http://blogs.msdn.com/b/oldnewthing/archive/2008/04/17/8399914.aspx#8408736
Get-ChildItem -Recurse . | where { $_.PSISContainer -and #( $_ | Get-ChildItem ).Count -eq 0 } | Remove-Item
or, more tersely,
gci -R . | where { $_.PSISContainer -and #( $_ | gci ).Count -eq 0 } | ri
credit goes to the posting author
from the command line:
for /R /D %1 in (*) do rd "%1"
in a batch file
for /R /D %%1 in (*) do rd "%%1"
I don't know if it's documented as such, but it works in W2K, XP, and Win 7. And I don't know if it will always work, but it won't ever delete files by accident.
This is a hybird of the above. It removes ALL files older than X days and removes any empty folders for the given path. To use simply set the days, folderpath and drive
#echo off
SETLOCAL
set days=30
set folderpath=E:\TEST\
set drive=E:
::Delete files
forfiles -p %folderpath% -s -d -%days% -c "cmd /c del /q #path "
::Delete folders
cd %folderpath%
%drive%
for /f "usebackq delims=" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"`
It will be worked fine. This is best way to delete old files and remove empty directories recursively.
following .bat file is,
forfiles /p [PATH] /s /m [FILE-PATTERN] /d -[DAYS] /c "cmd /c del #path"
for /f "delims=" %%d in ('dir [PATH] /s /b /ad ^| sort /r') do rd "%%d"
The placeholders needs to be replaced as follows (without the quotation marks):
[DAYS] = Max. age of the files in days, e.g. “10”
[PATH] = Path to search for old files and empty folders, e.g. “C:\Backup\”
[FILE-PATTERN] = Pattern that matches files to delete, e.g. “*.bkp”
The script has been successfully tested under Windows 7 and Windows Server 2003.
Install any UNIX interpreter for windows (Cygwin or Git Bash) and run the cmd:
find /path/to/directory -empty -type d
To find them
find /path/to/directory -empty -type d -delete
To delete them
(not really using the windows cmd prompt but it's easy and took few seconds to run)
#echo off
set /p "ipa= ENTER FOLDER NAME TO DELETE> "
set ipad="%ipa%"
IF not EXIST %ipad% GOTO notfound
IF EXIST %ipad% GOTO found
:found
echo DONOT CLOSE THIS WINDOW
md ccooppyy
xcopy %ipad%\*.* ccooppyy /s > NUL
rd %ipad% /s /q
ren ccooppyy %ipad%
cls
echo SUCCESS, PRESS ANY KEY TO EXIT
pause > NUL
exit
:notfound
echo I COULDN'T FIND THE FOLDER %ipad%
pause
exit
If you want to use Varun's ROBOCOPY command line in the Explorer context menu (i.e. right-click) here is a Windows registry import. I tried adding this as a comment to his answer, but the inline markup wasn't feasible.
I've tested this on my own Windows 10 PC, but use at your own risk. It will open a new command prompt, run the command, and pause so you can see the output.
Copy into a new text file:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Classes\directory\Background\shell\Delete Empty Folders\command]
#="C:\Windows\System32\Cmd.exe /C \"C:\Windows\System32\Robocopy.exe \"%V\" \"%V\" /s /move\" && PAUSE"
[HKEY_CURRENT_USER\Software\Classes\directory\shell\Delete Empty Folders\command]
#="C:\Windows\System32\Cmd.exe /C \"C:\Windows\System32\Robocopy.exe \"%V\" \"%V\" /s /move\" && PAUSE"
Rename the .txt extension to .reg
Double click to import.
for /r "D:\Music" /d %F in (.) do #dir /b "%F" | findstr "^" >nul || rmdir %~fF
D:\Fun is the folder that contains empty folders
double quotation in the case of space in folder name (no need in this example)
A more modern and easier solution is:
forfiles /p C:\Path\To\Folder /c "cmd /c if #isdir==TRUE rd #file"
This will attempt to execute rd on all the directories located in C:\Path\To\Folder. Directories that have content in them will not be deleted.
If you exclude /p C:\Path\To\Folder then it'll run in the current directory.
If you add /s (before the /c) then it'll also look in sub-directories.
The following .cmd is an experiment (that works) to:
Deletes empty directories and included "Old"(-1days) files under %temp% & C:\Windows\Temp folders,
makes an cmd output log to a .txt file, about fouded & deleted folders/files .
%temp% = C:\Users(user)\AppData\Local\Temp | %userprofile%\AppData\Local\Temp
code:
:: This is a .cmd file
:: Use to:
:: Writes a Log about Temporary files & folders.
:: Cleans 'Windows Temp' folders/files. (%userprofile%\AppData\Local\Temp -&- %windir%\Temp)
:: - a 'Cleaning_LOGs.txt' will be created or updated in Documents Library. (%userprofile%\Documents\Cleaning_LOGs.txt)
::
#echo off
title Log&CleanTemp
: Set the Path of 'Log file' (%LogPath% variable)
set "LogPath=%userprofile%\Documents\Cleaning_LOGs.txt"
:: Note: ">> path\file.txt 2>&1" redirects cmd output to <path\to>\<log_file.txt>, (will be created if does not exist)
:: (if exist, adds the new log at the end of the file, without deleting previous logs)
: Set 'C:\Windows\Temp' (%WinTemp% var.)
set "WinTemp=%windir%\Temp"
: Seperator [Header] with Date-Time between (any) previous Logs in <log_file.txt>
echo: >> %LogPath% 2>&1
echo ======================================== >> %LogPath% 2>&1
echo %date% - %time% >> %LogPath% 2>&1
echo: >> %LogPath% 2>&1
echo Log Path: %LogPath% (this text file) >> %LogPath% 2>&1
echo: >> %LogPath% 2>&1
: Report Output & Log
:: Writes a log about temporary files & folders.
:: Note: ( %temp% = C:\Users\<user>\AppData\Local\Temp = %userprofile%\AppData\Local\Temp )
:: ( 'WinTemp' = C:\Windows\Temp = %windir%\Temp )
echo: >> %LogPath% 2>&1
echo __________ Empty (0 size) , Old (-1days) files: >> %LogPath% 2>&1
ForFiles /p "%temp%" /s /d -1 /c "cmd /c if #fsize==0 ECHO #path " >> "%LogPath%" 2>&1
ForFiles /p "%WinTemp%" /s /d -1 /c "cmd /c if #fsize==0 ECHO #path " >> "%LogPath%" 2>&1
echo: >> %LogPath% 2>&1
echo __________ All Old (-1days) files: >> %LogPath% 2>&1
ForFiles /p "%temp%" /s /d -1 /c "cmd /c ECHO #path " >> "%LogPath%" 2>&1
ForFiles /p "%WinTemp%" /s /d -1 /c "cmd /c ECHO #path " >> "%LogPath%" 2>&1
:: Note: "ForFiles" /p=Path /s=SubDir /d=Days(dd) /c=cmd "forfiles /?" for info about command's Variables (#path, #file, etc.)
: Get permissions (unlock files/folders) (OPTIONAL)
:: Uncomment to make it work, IF needed.
::echo: >> %LogPath% 2>&1
::ForFiles /p "%temp%" /s /d -1 /c "cmd /c TAKEOWN /f * /r /d y && ICACLS #file /grant *S-1-3-4:F /t /c /l /q"
: Clean proper files & Log it
:: Test: ForFiles /p "%temp%\" /s /d -1 /c "cmd /c if #fsize==0 DEL /f /s /q #file" >> "%LogPath%" 2>&1
:: ERROR: Invalid argument/option - '#fsize==0'
echo: >> %LogPath% 2>&1
echo __________ Deleted files: >> %LogPath% 2>&1
forfiles /p %temp%\ /s /d -1 /c "cmd /c DEL /f /s /q #path" >> "%LogPath%" 2>&1
forfiles /p %WinTemp%\ /s /d -1 /c "cmd /c DEL /f /s /q #path" >> "%LogPath%" 2>&1
echo: >> %LogPath% 2>&1
echo __________ Deleted empty directories: >> %LogPath% 2>&1
for /f "delims=" %%d in ('dir %temp%\ /s /b /ad ^| sort /r') do RD "%%d" >> "%LogPath%" 2>&1
for /f "delims=" %%d in ('dir %WinTemp%\ /s /b /ad ^| sort /r') do RD "%%d" >> "%LogPath%" 2>&1
:: Note: 'RD' = Remove-Directory (delete)
: Open Log file
:: this opens the log file [(my) Documents\Cleaning_LOGs.txt]
explorer.exe %LogPath%
:: https://stackoverflow.com/questions/7831286/how-to-delete-empty-folders-using-windows-command-prompt/46617314#46617314
Note that:
The trigger to Experiment with this, as part of a 'pre-process', was to prevent the specific (obsolete) driver of the (also obsolete) sound card from automatically reinstalling at each boot. And clean (ghosted) hidden Devices and more other. (...) (this note was just about to get an idea for the use)
So, in a few words:
This is the part that cleans up the 'temp' garbage left behind and gives a report.
well, just a quick and dirty suggestion for simple 1-level directory structure without spaces, [edit] and for directories containing only ONE type of files that I found useful (at some point from http://www.pcreview.co.uk/forums/can-check-if-folder-empty-bat-file-t1468868.html):
for /f %a in ('dir /ad/b') do if not exist %a\*.xml echo %a Empty
/ad : shows only directory entries
/b : use bare format (just names)
[edit] using plain asterisk to check for ANY file (%a\* above) won't work, thanks for correction
therefore, deleting would be:
for /f %a in ('dir /ad/b') do if not exist %a\*.xml rmdir %a
This can be easily done by using rd command with two parameters:
rd <folder> /Q /S
/Q - Quiet mode, do not ask if ok to remove a directory tree with
/S
/S - Removes all directories and files in the specified directory
in addition to the directory itself. Used to remove a directory tree.
I want to have a batch file that will delete all the folders and files in my cache folder for my wireless toolkit.
Currently I have the following:
cd "C:\Users\tbrollo\j2mewtk\2.5.2\appdb\RMS"
del *.db
This will delete all .db files in my RMS directory, however I want to delete every single thing from this directory. How can I do this?
Use:
Create a batch file
Copy the below text into the batch file
set folder="C:\test"
cd /d %folder%
for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
It will delete all files and folders.
del *.* instead of del *.db. That will remove everything.
IF EXIST "C:\Users\tbrollo\j2mewtk\2.5.2\appdb\RMS" (
rmdir "C:\Users\tbrollo\j2mewtk\2.5.2\appdb\RMS" /s /q
)
This will delete everything from the folder (and the folder itself).
I just put this together from what morty346 posted:
set folder="C:\test"
IF EXIST "%folder%" (
cd /d %folder%
for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
)
It adds a quick check that the folder defined in the variable exists first, changes directory to the folder, and deletes the contents.
del *.* will only delete files, but not subdirectories. To nuke the contents of a directory, you can use this script:
#echo off
setlocal enableextensions
if {%1}=={} goto :HELP
if {%1}=={/?} goto :HELP
goto :START
:HELP
echo Usage: %~n0 directory-name
echo.
echo Empties the contents of the specified directory,
echo WITHOUT CONFIRMATION. USE EXTREME CAUTION!
goto :DONE
:START
pushd %1 || goto :DONE
rd /q /s . 2> NUL
popd
:DONE
endlocal
The pushd changes into the directory of which you want to delete the children. Then when rd asks to delete the current directory and all sub directories, the deletion of the sub directories succeed, but the deletion of the current directory fails - because we are in it. This produces an error which 2> NUL swallows. (2 being the error stream).
You can do this using del and the /S flag (to tell it to recurse all files from all subdirectories):
del /S C:\Path\to\directory\*
The RD command can also be used. Recursively delete quietly without a prompt:
#RD /S /Q %VAR_PATH%
Rmdir (rd)
set "DIR_TO_DELETE=your_path_to_the_folder"
IF EXIST %DIR_TO_DELETE% (
FOR /D %%p IN ("%DIR_TO_DELETE%\*.*") DO rmdir "%%p" /S /Q
del %DIR_TO_DELETE%\*.* /F /Q
)
Use
set dir="Your Folder Path Here"
rmdir /s %dir%
mkdir %dir%
This version deletes without asking:
set dir="Your Folder Here"
rmdir /s /q %dir%
mkdir %dir%
Example:
set dir="C:\foo1\foo\foo\foo3"
rmdir /s /q %dir%
mkdir %dir%
This will clear C:\foo1\foo\foo\foo3.
(I would like to mention Abdullah Sabouin's answer. There was a mix up about me copying him. I did not notice his post. I would like to thank you melpomene for pointing out errors!)
Try the following; it works for me.
I have an application which dumps data in my "C:\tmp" folder, and the following works the best for me. It doesn't even ask Yes or No to delete the data. I have made a schedule for it to run after every 5 minutes
cd "C:\tmp"
del *.* /Q
Better yet, let's say I want to remove everything under the C:\windows\temp folder.
#echo off
rd C:\windows\temp /s /q
You could use robocopy to mirror an empty folder to the folder you are clearing.
robocopy "C:\temp\empty" "C:\temp\target" /E /MIR
It also works if you can't remove or recreate the actual folder.
It does require an existing empty directory.
I would like to suggest using simple tool like cleardir. So, in batch file you can write:
cleardir path/to/dir
And you'll get empty directory dir. A bit slow, but still resolves the "problem".
I'm an author of the tool =)
The easiest way is:
Create *.txt file
Write:
rmdir /q /s . dir
Save file as *.bat in folder which you want to clear (you can call the file NUKE.bat)
Turn it on
WARNING!
THIS DELETES EVERYTHING IN THE FOLDER WHERE IT IS WITHOUT ASKING FOR CONFIRMATION!!!
SO CHOOSE WISELY PLACE FOR SAVING IT.
Easy simple answer :
C:
del /S /Q C:\folderName\otherFolderName\*
C: Important in case you have to switch from D: to C: or C: to D: (or anything else)
/S Recursive, all subfolders are deleted along
/Q If you don't activate quiet mode, prompt will ask you to type y for every subfolders... you don't want that
Be carful, it's drastic.
You cannot delete everything with either rmdir or del alone:
rmdir /s /q does not accept wildcard params. So rmdir /s /q * will error.
del /s /f /q will delete all files, but empty subdirectories will remain.
My preferred solution (as I have used in many other batch files) is:
rmdir /s /q . 2>NUL
Just a modified version of GregM's answer:
set folder="C:\test"
cd /D %folder%
if NOT %errorlevel% == 0 (exit /b 1)
echo Entire content of %cd% will be deleted. Press Ctrl-C to abort
pause
REM First the directories /ad option of dir
for /F "delims=" %%i in ('dir /b /ad') do (echo rmdir "%%i" /s/q)
REM Now the files /a-d option of dir
for /F "delims=" %%i in ('dir /b /a-d') do (echo del "%%i" /q)
REM To deactivate simulation mode remove the word 'echo' before 'rmdir' and 'del'.
#echo off
#color 0A
echo Deleting logs
rmdir /S/Q c:\log\
ping 1.1.1.1 -n 5 -w 1000 > nul
echo Adding log folder back
md c:\log\
You was on the right track. Just add code to add the folder which is deleted back again.