check the existence of the folder and delete the temp files - batch-file

I use batch file commands to delete the temp files in the system. The command works OK.
This code, works normally, but there is a flaw:
FOR /D %%p IN ("C:\Temp\*.*") DO rmdir "%%p" /s /q
cd c:\temp
del /F /s /q *.* >c:\DelTempLog.txt
rd /s /q %systemdrive%\$Recycle.bin >c:\DelTempLog.txt
FOR /D %%p IN ("C:\Windows\Installer\$PatchCache$\*.*") DO rmdir "%%p" /s /q
cd C:\Windows\Installer\$PatchCache$
del /F /s /q *.* >c:\DelTempLog.txt
FOR /D %%p IN ("C:\Windows\Temp*.*") DO rmdir "%%p" /s /q
cd C:\Windows\Temp
del /F /s /q *.* >c:\DelTempLog.txt
del /q /s %tmp% >c:\DelTempLog.txt
Today I faced an exception where c:\temp folder did not exist on the server.
It deleted half of the files under c:\windows\system32.
I want to add an IF command after changing the DIR before deleting anything.
Also, please advise me how to do logging activity in a better way.

At an elementary level if you specify the full path on the command line then it cannot delete files from anywhere else.
del /F /s /q "c:\temp\*.*?"
There is also no need to change the directory before issuing the command.
The ? suppresses a prompt that asks if you are sure that you want to delete all files.

How about, before your batch-as-it-stands, you try
md c:\temp 2>nul
if not exist c:\temp\. echo No c:\temp!&goto :eof

#echo off
setlocal enableextensions disabledelayedexpansion
set "logFile=c:\deltemplog.txt"
(for %%a in (
"c:\temp" "c:\windows\temp" "%temp%"
"%systemdrive%\$Recycle.bin" "C:\Windows\Installer\$PatchCache$"
) do if not exist "%%~a\" (
echo [ ERROR ]: "%%~a" does not exist
) else pushd "%%~a" && (
echo [ pushd ]: changed to "%%~a"
echo rmdir . /s /q
popd
) || (
echo [ ERROR ]: Failed to change to "%%~a"
)
) > "%logFile%"
For each folder in the list, change to it and if the command did not fail, remove the current folder (this will remove the content, not the folder, as it is the current one).
The rmdir commands are only echoed. If the output (in the log file) is correct, remove the echo command that prefixes rmdir

My preference is to use the %CD% built-in value, then try to move to the folder and see if it worked, as in:
set CURDIR=%CD%
pushd C:\Temp
if '%CD%'=='%CURDIR%' (
echo Failed to move to C:\Temp
) else (
[code to do your deletions]
)
popd
I prefer to push and pop a directory rather than a hard CD to it, simply because then you can always get back to where you were without having to know where that was.

Related

How to fix the error "The filename, directory name, or volume label syntax is incorrect." while running my bat file?

I was trying to delete C:\Users\%USERPROFILE%\AppData\Local\Temp
and it shows the error:
The filename, directory name, or volume label syntax is incorrect.
This is the code:
#Echo off
del /s /q "C:\Windows\Temp\*.*"
del /s /q "C:\Windows\Prefetch\*.*"
del /s /q "C:\Users\%USERPROFILE%\AppData\Local\Temp\*.*"
for /d %%p in ("C:\Windows\Prefetch\*.*") do rmdir "%%p" /s /q
for /d %%p in ("C:\Windows\Temp\*.*") do rmdir "%%p" /s /q
for /d %%p in ("C:\Users\%USERPROFILE%\AppData\Local\Temp\*.*") do rmdir "%%p" /s /q
ipconfig /flushdns
pause
This is the output on running the batch file:
The filename, directory name, or volume label syntax is incorrect.
Windows IP Configuration
Successfully flushed the DNS Resolver Cache.
Press any key to continue . . .
The solution is quite simple on using this code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
%SystemRoot%\System32\reg.exe QUERY "HKLM\System\CurrentControlSet\Control\Session Manager" /V PendingFileRenameOperations >nul 2>nul && goto NoDelInfo
pushd "%SystemRoot%\Temp" 2>nul && ( rd /Q /S "%SystemRoot%\Temp" 2>nul & popd )
pushd "%SystemRoot%\Prefetch" 2>nul && ( rd /Q /S "%SystemRoot%\Prefetch" 2>nul & popd )
pushd "%TEMP%" 2>nul && ( rd /Q /S "%TEMP%" 2>nul & popd )
%SystemRoot%\System32\ipconfig.exe /flushdns
goto EndBatch
:NoDelInfo
echo There are pending file rename operations.
echo/
echo Please first restart Windows and then run "%~nx0" once again.
echo/
:EndBatch
endlocal
pause
For a full explanation of the three command lines to clear the three folders see:
How to delete files/subfolders in a specific directory at the command prompt in Windows?
The directories for temporary files should never be cleared on pending file/folder rename operations currently registered done by Windows on next start to complete an installation or an uninstall using perhaps files currently stored in one of the two directories for temporary files.
See also the Wikipedia article about the predefined Windows Environment Variables displayed with their values on running set in a command prompt window.
In general it is better to run as administrator the Disk Cleanup tool of Windows as it can delete much more files no longer needed as this batch file.

Deleting Folder Contents but not the folder

I have a folder C:\Epson Scans, I am trying to figure out how to write a script that will delete the contents of the folder but leave the folder intact. I have figured out how to delete the entire folder and I could recreate it. But I wanted to know if anyone knows a way of just deleting the contents inside the folder and not actually deleting the folder. Any help with this would be greatly appreciated!
Edit: Inserting working code so I can loop through many computers and do it at once. Will someone please tell me why the code is not working where I have inserted it?
#echo off
setlocal enabledelayedexpansion
set Delete_success=0
set total=0
for /F %%G in (pclist.txt) do (
set /a total+=1
pushd "C:\Epson Scans" || exit /B 1
for /D %%I in ("*") do (
rd /S /Q "%%~I"
)
del /Q "*"
popd
if !ERRORLEVEL!==0 (
set /a Delete_success+=1
) else (
echo EpsonDelete copy failed on %%G>>EpsonDelete_FailedPCs.txt
)
)
echo Delete Success: %Delete_success%/%total% >>EpsonDelete_FileCopy.txt
del deletes files only, so del /S /Q "C:\Epson Scans" deletes all files in the given folder and sub-folders (due to /S).
rmdir deletes folders, so specifying rmdir /S /Q "C:\Epson Scans" also deletes the folder Epson Scans itself.
Of course you could execute mkdir "C:\Epson Scans" afterwards to newly create the deleted folder again1, but this was not asked for. So the correct answer is to use a for /D loop over C:\Epson Scans and delete each folder it contains, and then use del /Q to delete the files:
pushd "C:\Epson Scans" || exit /B 1
for /D %%I in ("*") do (
rd /S /Q "%%~I"
)
del /Q "*"
popd
Note that rd is the same as rmdir -- see also this post: What is the difference between MD and MKDIR batch command?
1) Regard that some folder attributes get lost if you do that, for example the owner. Also the case is lost as Windows treats paths case-insensitively.
del /S C:\Epson Scans*
(use S to delete all files and folders in selected folder)
del C:\Epson Scans*.*
if this is batch file you might want to add /Q in order to avoid a delete confirmation dialog:
del C:\Epson Scans\*.* /Q

Delete files and subfolders in the folders "tmp" and "cache"

I want to use this script below to clean out "tmp" and "cache" folders in websites like "C:\Storage\Websites\Site1".
It tries to delete files and subfolders in "C:\Storage\Websites\Site1\tmp" and "C:\Storage\Websites\Site1\cache".
Which is right, but it also tries to delete files and subfolders in, for example, "C:\Storage\Websites\Site1\MySpecialLittleProgram\tmp" and, for example, "C:\Storage\Websites\Site1\MySpecialLittleProgram\cache".
Which is wrong. It should only clean up the "tmp" and "cache" folder in the root of the website and not in other subfolders.
If I delete the /s parameter in 'dir /a:d /b /s tmp cache' it will not find anything.
How can I do this part?
(I have deleted the /q parameter in the file deleting part and the folder removing part if anyone copies my script.)
#echo off
call:CleanUp "C:\Storage\Websites"
echo.&pause&goto:eof
::--------------------------------------------------------
::-- Function section starts below here
::--------------------------------------------------------
:CleanUp
IF EXIST %~1 (
cd /d %~1
FOR /f "tokens=*" %%i in ('dir /a:d /b /s tmp cache') DO (
echo %%i
::DELETING FILES I FOLDERS AND SUBFOLDERS
del %%i /s
::DELETING NOW EMPTY FOLDERS AND SUBFOLDERS
FOR /D %%p IN ("%%i\*.*") DO rmdir "%%p" /s
)
)
goto:eof
UPDATE:
I updated my code to be (it is working now):
#echo off
call:CleanUp "C:\Storage\Web"
call:CleanUp "C:\Storage\Web-IIS"
goto:eof
::--------------------------------------------------------
::-- Function section starts below here
::--------------------------------------------------------
:CleanUp
IF EXIST %~1 (
cd /d %~1
FOR /f "tokens=*" %%i in ('dir /a:d /b') DO (
IF EXIST %%i\tmp (
del %%i\tmp /s /q
FOR /D %%p IN ("%%i\tmp\*.*") DO rmdir "%%p" /s /q
)
IF EXIST %%i\cache (
del %%i\cache /s /q
FOR /D %%p IN ("%%i\cache\*.*") DO rmdir "%%p" /s /q
)
)
)
goto:eof
This should remove the files in those two locations:
#echo off
del "C:\Storage\Websites\Site1\tmp\*.*" /a /s
del "C:\Storage\Websites\Site1\cache\*.*" /a /s
From your comment, this may be what you need to do: remove the echo keyword after testing it to see the commands on the console that would be executed.
#echo off
cd /d "C:\Storage\Websites"
for /d %%a in (*) do (
for %%b in (tmp cache) do (
pushd "%%~fa\%%b" 2>nul && (echo rd /s /q "%%~fa\%%b" 2>nul & popd)
)
)
pause
I suggest to use rmdir or rd for this task:
rd "C:\Storage\Websites\Site1\tmp" /S /Q
md "C:\Storage\Websites\Site1\tmp"
rd "C:\Storage\Websites\Site1\cache" /S /Q
md "C:\Storage\Websites\Site1"
Command rd with options /S for all subdirectories and /Q for quiet deletes also tmp and cache, but those 2 directories can be easily recreated using command md although I'm quite sure that this would not be really necessary here as the application creating tmp and cache would do it also automatically.
If that is not what you want, please show as directory listings with files and folders in one of the two directories before cleanup and after cleanup.

Command to delete files in UNC path

Hi I tried below command to delete files in UNC path
set folder="\\SERVERNAME\Publish"
cd /d %folder%
for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
But I got error saying:
UNC paths are not supported. Defaulting to Windows Directory
Somehow I need to delete files that are residing in Server's shared path using batch command. Any help appreciated.
edited 2015-09-16 - Original answer remains at the bottom
Code reformated to avoid removal of non desired folders if the mapping fails. Only if the pushd suceeds the removal is executed.
set "folder=\\SERVERNAME\Publish"
pushd "%folder%" && (
for /d %%i in (*) do rmdir "%%i" /s /q
popd
)
original answer:
set "folder=\\SERVERNAME\Publish"
pushd "%folder%"
for /d %%i in (*) do rmdir "%%i" /s /q
popd
pushd will create a drive mapping over the unc path and then change to it. Then, all the operations are over drive:\folders. At the end popd will remove the drive assignation.
This deletes all files with name like 'ms' and over a year.
#echo off
set "year=-365"
PushD "\\SERVERNAME\FolderName" && (
"forfiles.exe" /s /m "*_ms_*" /d %year% /c "cmd /c del #file"
) & PopD

Batch file won't delete contents of a folder

I'm trying to make a program that will delete some files and perfrom rutine maintance on a computer by just clickin on one file. I'm testing it as I'm going along and realized that it's not deleting the folders. I want to delete everything within the folders but not the folders themselves. Here is my code so far:
#echo off
title SYSTEM Optimiation
echo Deleting Temp Folder
del /q /f "C:\Documents and Settings\%username%\Local Settings\TEMP"
echo.
echo DONE
echo.
echo Deleting Download folder
del /q /f "C:\Documents and Settings\%username%\My Documents\Downloads"
echo.
echo DONE
echo.
echo.
echo Hit any key to exit.
pause >nul
Try using wildcards and the /s switch on del:
del /q /s /f "%userprofile%\My Documents\Downloads\*"
but this will probably leave directories inside intact, but empty. Another option would be the quite explicit:
for /d /r "%userprofile%\My Documents\Downloads" %%x in (*) do rd /s /q "%%x"
for /r "%userprofile%\My Documents\Downloads" %%x in (*) do del /f "%%x"
Here much simpler than above. Current directory will be locked and therefore will not be deleted with others.
cd %Temp% && rmdir /s /q .

Resources