How to delete a single file if older than x days? - batch-file

I need to delete a single file before starting a program, but this should be done only when it's older than a day.
At the moment I execute always in a command prompt window:
del /f filepath
*run program*
I know, there is this option to do it for multiple files via batch:
ForFiles /p "path" /d -X /c "cmd /c del #file"
But I want to do this only for a specific file, do I have to use forfiles or is there another little bit faster option without iteration?

Here is your code:
forfiles /p "path" /m "file name" /d -Number of the days older mean the value of your X days /c "cmd /c del /f /q /a #file"
You got the code in your question hard coded. The /s switch of forfiles iterates through all the sub folders of given path. So there is no use of that switch. And the value of /d switch deletes files more older than 30 days, but you have wanted anonymous X days. Change them and your code will work. For more help, start cmd and type forfiles /?.

Related

Batch script - dir /b is including directory names and empty lines in output file

I run this script to list backup files older than 8 days and delete them in a server, and it behaving weird recently. Please see below
::Find backup files older than 8 days
::/p Specifies the path from which to start the search.
::/s Instructs the forfiles command to search into subdirectories recursively.
::/d Selects files with a last modified date within the specified time frame.
::/c Carries out the command specified by String and then stops.
::/b Displays a bare list of directories and files, with no additional information.
PUSHD \\SERVER_NAME\M$\MSSQL
FORFILES /P Backup /s /d -8 /C "cmd /c dir /B #file">K:\ScriptLogs\OutPut
POPD
This was working fine recently until I created more folders inside \SERVER_NAME\M$\MSSQL\Backup like FULL, DIFF, LOG as
\\SERVER_NAME\M$\MSSQL\Backup\FULL
\\SERVER_NAME\M$\MSSQL\Backup\DIFF
\\SERVER_NAME\M$\MSSQL\Backup\LOG
And the K:\ScriptLogs\OutPut file is now including the folder name FULL as below
FULL
SERVER_NAME_DB_DIFF_2021_06_10_040135.diff
SERVER_NAME_DB_DIFF_2021_06_11_040124.diff
SERVER_NAME_DB_DIFF_2021_06_12_040213_1.diff
I'm not able to understand why it is including FULL in the output list (if my cmd is wrong it should include DIFF and LOG too).
And when i modified the code as below
PUSHD \\SERVER_NAME\M$\MSSQL
FORFILES /P Backup /s /d -8 /C "cmd /c dir /A-D /B #file">K:\ScriptLogs\OutPut
POPD
It gives error as below, and output file is not including FULL now (as /A-D excluded Dir's)
K:\DBScripts>PUSHD \\SERVER_NAME\M$\MSSQL
W:\MSSQL>FORFILES /P Backup /s /d -8 /C "cmd /c dir /A-D /B #file" 1>K:\ScriptLogs\OutPut
File Not Found
File Not Found
W:\MSSQL>POPD
My concern here is why it is including FULL directory name in the older code version and the code run gives error with new version. Thanks for your help.
Thanks #compo ....
PUSHD \\SERVER_NAME\M$\MSSQL
FORFILES /P Backup /S /D -%NUMBER_OF_DAYS% /C "cmd /Q /D /C \"If #IsDir==FALSE For %%G In (#File) Do Echo %%~G\"" 1>K:\ScriptLogs\OutPut-%dtStamp%
POPD
This fixed the issue.

Is there a way to perform a negative search mask to forfiles?

I know how to utilize search masks in the forfiles command to target files of a particular extension, but I am working with a case where I want to avoid a particular extension and catch everything else.
Is there an easy way to achieve this with the forfiles command or will I need to write a custom for loop to handle this process? I am not looking to run a command like below which would force me to define my search masks before hand.
for %G in (.txt, .edi, .csv) do forfiles -p "C:abc\del" -s -m *%G -d -10 -c "cmd /c echo #path"
My use case is removing all files that are not encrypted from a directory recursively based on a single extension. This would be my negative value.
This batch file script command deletes everything older than 30 days if the filename does not end in PDF. It uses the 2003 version of forfiles in a Windows 7 cmd shell.
forfiles can not use reg exps, it only processes simple wildcards for masks. This is inefficient but ok for a small number of files.
for /f "delims=" %%X in ('dir /b %DIRNAME% ^|grep -vi pdf$') do forfiles /p %DIRNAME% /m "%%X" /d %DAYNUM% /c "cmd /c del #FILE" ```
As per #Compo's comments to my question, an approach to applying a negative search mask to the forfiles command would be to add a filter to the cmd implementation after the fact like so:
forfiles /P %localDir% /S /M *.* /C "cmd /c if not #EXT == %ignoredExtension% echo #PATH
However, #Compo raised a valid concern that this implementation would cause a new cmd.exe instance to be opened for every file found. In instances where the file count is fixed or known to be constant this may be a decent approach, but a more efficient alternative that is able to be scaled would be to create a for loop manually that applies this filter at the for loop instance before making the call to the do operations like so:
For /F "Delims=" %%G In ('dir /A-D^|FindStr /VE %ignoredExtensions%')Do #echo %%G

Batch file to delete all text files in a folder over 10 days old except certain ones

I'm new to batch files, trying to write one that will delete all .txt files in a folder over 10 days old EXCEPT one called template.txt. How is this done? I have the below but it deletes ALL txt files over 10 days. Appreciate your help.
forfiles /p "C:\test" /s /m *.txt /c "cmd /c del #path" /d -10
Just implement the contition into the command line run by forfiles, like this:
forfiles /S /P "C:\test" /M "*.txt" /D -10 /C "cmd /C if #isdir==FALSE if /I not #file==0x22template.txt0x22 del #path"
The if #isdir==FALSE part is to exclude any directories from being processed further in case there are some with .txt at the end of their names (although quite unlikely), because forfiles enumerates both files and directories.
if /I not #file==0x22template.txt0x22 becomes if /I not "<name of currently iterated item>"=="template.txt" and excludes files named template.txt from being deleted. The /I option makes the comparison case-insensitive, like Windows also treats file and directory paths.

Deletion Batch file but receive cannot find desktop.ini

I've created a simple batch file to delete files over 14 days which is a simple command as most of you probably know so it's doing the below
forfiles /p "C:\%userprofile%\Downloads" /s /m *.* /c "cmd /c Del #path" /d -14
but I keep receiving could not find C:\User\%userprofile%\downloads\desktop.ini
So I assume it's searching for the desktop.ini file but I have all folders and files unhidden. Is there a way to prevent it looking for that file and just doing as a I ask it?
Any help would be appreciated.
As Mike Nakis suggests, del is probably failing on desktop.ini because that file is typically set +ash (archive, system, and hidden). The easiest solution would be just to ignore it. It's harmless anyway.
forfiles /p "%userprofile%\Downloads" /s /m *.* /c "cmd /c Del #path 2>NUL" /d -14
If it really bothers you and you insist on deleting it, then remove the system attribute.
attrib -r -s -h -a "%userprofile%\Downloads\*"
forfiles /p "%userprofile%\Downloads" /s /m *.* /c "cmd /c del #path" /d -14
... but it'll probably just get re-created eventually anyway. I'd just ignore it.
What do you mean when you say that you have all folders and files unhidden? You have probably instructed the windows explorer to also show hidden files, but that does not mean that the files are not hidden.
You have two options: for each file that you are about to delete, either use the attrib command to make sure it is not hidden prior to deleting it, or play with the /A option of the del command to make it delete everything, even hidden files.

Forfiles Batch Script (Escaping # character)

I'm working on a batch script that will let me delete files older then a set period using forfiles. For now, I'm aiming at printing the files that will be deleted.
The forfiles invocation I'm using works flawlessly from a cmd.exe shell, but as soon as I embed it into a batch script, it barfs. I suspect that this is due to the # character not being escaped properly, but I'm not certain.
The command I'm running is:
forfiles /S /P "r:\" /m *.bak /d -10 /c "cmd /c echo #PATH"
And it results in the following error:
ERROR: Invalid argument/option - '#PATH'
Type "FORFILES /?" for usage.
I've googled all over the place and tried a few different schemes for escaping the #PATH component. Everything from ##PATH, to \"#PATH\" with no results.
Any help would be appreciated!
I should also note that I'm basing a lot of my knowledge of forfiles from here.
I had the same problem until I removed the quotation marks around the directory path , like this:
forfiles /S /P r:\ /m *.bak /d -10 /c "cmd /c echo #PATH"
Hope that helps.
Try trimming the trailing \ from your /P path. Then you should be able to use quotes to encapsulate a path that includes a space.
This an old question but I've got a different answer... in case anyone needs it.
When using 'forfiles', the path (written after /p) CAN be between quotation marks. However, it must not end with a slash.
If you want to run 'forfiles' for the root directory of a drive:
forfiles /p "C:" /c "cmd /c echo #file"
If you want to process files in a different directory...
forfiles /p "C:\Program Files" /c "cmd /c echo #file"
In other words, the safest approach is:
Always use quotation marks (because folders with spaces, like 'Program Files', will still work)
Always omit the last trailing slash
forfiles /p "C:\Path\Without\Trailing\Slash"
Best practice would be to use double-quote marks around the path (/P) parameter to handle paths with spaces.
The issue occurs when the substitution variable contains a trailing backslash. The backslash 'escapes' the quote, causing FORFILES to mis-interpret the rest of the command line.
By convention, the path to a directory does not need the trailing backslash, the one exception to this being the root directory. Specifying only the drive letter and a colon C: does NOT refer to the root - rather it refers to the 'current directory' for that drive. To refer to the root, one must use the trailing backslash C:\.
My solution is as follows:
When using FORFILES, append a . prior to the closing " of the /P parameter e.g.
FORFILES /P "%somePath%." /C "CMD /C ECHO #path"
After substitution, this leads to paths of the form C:\.,C:\TEMP. or C:\TEMP\.. All of these are treated correctly by FORFILES and also DIR.
I have not tested all the possible FORFILES substitution variables but #path appears to be unaffected by the addition of the .
I found there are two versions of FORFILES, one is 1998 version (thanks to Emmanuel Boersma), and the other one is 2005 version (modified date time show it).
FORFILES v 1.1 - by Emmanuel Boersma - 4/98
Syntax : FORFILES [-pPath] [-mSearch Mask] [-ccommand] [-dDDMMYY] [-s]
-pPath Path where to start searching
-mSearch Mask Search files according to <Search Mask>
-cCommand Command to execute on each file(s)
-d[+|-][DDMMYY|DD] Select files with date >= or <=DDMMYY (UTC)
or files having date >= or <= (current date - DD days)
-s Recurse directories
-v Verbose mode
The following variables can be used in Command :
#FILE, #PATH, #RELPATH, #ISDIR, #FSIZE, #FDATE, #FTIME
Default : <Directory : .> <Search Mask : *.*> <Command : "CMD /C Echo #FILE">
Examples :
FORFILES -pc:\ -s -m*.BAT -c"CMD /C Echo #FILE is a batch file"
FORFILES -pc:\ -s -m*.* -c"CMD /C if #ISDIR==TRUE echo #FILE is a directory"
FORFILES -pc:\ -s -m*.* -d-100 -c"CMD /C Echo #FILE : date >= 100 days"
FORFILES -pc:\ -s -m*.* -d-010193 -c"CMD /C Echo #FILE is quite old!"
Each version have their unique syntax.
FORFILES [/P pathname] [/M searchmask] [/S]
[/C command] [/D [+ | -] {MM/dd/yyyy | dd}]
Description:
Selects a file (or set of files) and executes a
command on that file. This is helpful for batch jobs.
Parameter List:
/P pathname Indicates the path to start searching.
The default folder is the current working
directory (.).
/M searchmask Searches files according to a searchmask.
The default searchmask is '*' .
/S Instructs forfiles to recurse into
subdirectories. Like "DIR /S".
/C command Indicates the command to execute for each file.
Command strings should be wrapped in double
quotes.
The default command is "cmd /c echo #file".
The following variables can be used in the
command string:
#file - returns the name of the file.
#fname - returns the file name without
extension.
#ext - returns only the extension of the
file.
#path - returns the full path of the file.
#relpath - returns the relative path of the
file.
#isdir - returns "TRUE" if a file type is
a directory, and "FALSE" for files.
#fsize - returns the size of the file in
bytes.
#fdate - returns the last modified date of the
file.
#ftime - returns the last modified time of the
file.
To include special characters in the command
line, use the hexadecimal code for the character
in 0xHH format (ex. 0x09 for tab). Internal
CMD.exe commands should be preceded with
"cmd /c".
/D date Selects files with a last modified date greater
than or equal to (+), or less than or equal to
(-), the specified date using the
"MM/dd/yyyy" format; or selects files with a
last modified date greater than or equal to (+)
the current date plus "dd" days, or less than or
equal to (-) the current date minus "dd" days. A
valid "dd" number of days can be any number in
the range of 0 - 32768.
"+" is taken as default sign if not specified.
/? Displays this help message.
Examples:
FORFILES /?
FORFILES
FORFILES /P C:\WINDOWS /S /M DNS*.*
FORFILES /S /M *.txt /C "cmd /c type #file | more"
FORFILES /P C:\ /S /M *.bat
FORFILES /D -30 /M *.exe
/C "cmd /c echo #path 0x09 was changed 30 days ago"
FORFILES /D 01/01/2001
/C "cmd /c echo #fname is new since Jan 1st 2001"
FORFILES /D +3/19/2012 /C "cmd /c echo #fname is new today"
FORFILES /M *.exe /D +1
FORFILES /S /M *.doc /C "cmd /c echo #fsize"
FORFILES /M *.txt /C "cmd /c if #isdir==FALSE notepad.exe #file"
Have a nice time making "Batch File" more sophisticated. :)
Put forfiles.exe to get it to work right, otherwise it will not pass the #variables when you use a batch file. Forfiles will work if you are at the command prompt, but when you run it in a batch file the variables don't work right unless you put: forfiles.exe.
Here is an example that deletes some txt files older than 30 days
forfiles.exe /P c:\directory\ /M *.txt /C "cmd /c del #path" /d -30
dir *.* > C:\path\dummy%date:~4,2%%date:~7,2%%date:~10,4%.DAT
dir *.* > C:\path\dummy%date:~4,2%%date:~7,2%%date:~10,4%.csv
forfiles -p C:\path\ -m *.DAT /d -50 /c "cmd /c del /Q #path"
forfiles -p C:\path\ -m *.csv /d -50 /c "cmd /c del /Q #path"
Replace the .dat and .csv files what u want to delete.
-50 delete older then 50 days
This is the windows batch file
DID NOT WORK
FORFILES /P %deletepath% /M *.%extension% /D -%days% /C "cmd /c del #PATH"
DID WORK
FORFILES /P %deletepath% /M *.%extension% /D -%days% /C "cmd /c del #path"
#path in lower case works.
After searching everywhere I came across the answer in my own testing. Using the latest version on server 2012 R2 I tried changing the #PATH to lower case. This fixed it for me.
Good luck!

Resources