You will need an interim environment variable, say VAR
, and delayed expansion to accomplish that.
At first let us build the code that needs to be executed in the forfiles
loop:
if @isdir==FALSE (
set VAR=@relpath
if not #!VAR:%search%=!==#!VAR! (
del /Q @path
echo @path deleted.
)
)
This does the following steps:
- check whether the matched item is a file, skip the rest otherwise;
- assign the value of
@relpath
to the variable VAR
; note that @relpath
is expanded to a relative path enclosed in ""
;
- check whether the expanded relative path contains at least one instance of the search string, skip the rest if not; note that the search is done in a case-insensitive manner;
- delete the matched path, return the related log message;
@path
already contains the file name plus extension, so you do not need @file
;
Now let us write the above code as a single line and put it together with forfiles
:
set "loglocation=C:\Tools\PurgeOldFiles\log\DELETEOLD_XML_IMG.txt"
set "olderthan=30"
set "source=X:\Test"
set "extension=XML"
set "search=img"
forfiles /S /P "%source%" /M "*.%extension%" /D -%olderthan% /C "cmd /V:ON /C 0x22if @isdir==FALSE ((set VAR=@relpath) & if not #!VAR:%search%=!==#!VAR! (del /Q @path & echo @path deleted.))0x22" >> "%loglocation%"
The /V
switch of cmd
enables delayed expansion; the !VAR!
syntax makes use of it (opposed to %VAR%
). Type cmd /?
for more information on that.
Notes:
The search for the img
substring does not care about where (at which level in the path) a match is found, nor does it detect how many matches occur.
Be aware that the switch /S
of forfiles
makes it to enumerate the given directory recursively.