Comparing output of ForFiles - batch-file

I'm trying to make a simple script that will output the names of all subfolders, except for one. I'm having trouble doing the string comparison to remove that one folder.
Here's a basic folder breakdown:
C
Backup
.sync
folder1
folder2
Here's a basic example of code that works 90%:
ForFiles /P C:\Backup /C "CMD /C echo #FILE"
And here's the output of this command (the quotation marks are in the output itself):
".sync"
"folder1"
"folder2"
To give a brief explanation of the code, basically ForFiles will run through the files and subfolders at the given path (specified by /P C:\Backup). /C then specifies a command, which is in double quotes - echo #FILE will then output the name of the file. The actual code I'm running is more complex than this, but this will suffice as a minimum example showing my problem. I do not want to output the name of the .sync folder, because it's used by another program and should not be touched.
So, what I want to do is put an "if" statement in the command, so that not everything will be output. In pseudocode, this would be "if the name of the folder is not .sync, output the name of the folder". However, this appears to be more complex because of the quotation marks, which I guess I have to escape - but I have not had any luck with it. Here are some things I've tried:
Outputs all files, including .sync:
ForFiles /P C:\Backup /C "CMD /C if NOT #FILE == .sync echo #FILE"
ForFiles /P C:\Backup /C "CMD /C if NOT #FILE == ".sync" echo #FILE"
ForFiles /P C:\Backup /C "CMD /C if NOT #FILE == '.sync' echo #FILE"
Gives an error because of the double double quotes (one method of escaping the double quotes, found on Stack Overflow)
ForFiles /P C:\Backup /C "CMD /C if NOT #FILE == "".sync"" echo #FILE"
Outputs all files, including .sync - using the ^ symbol was the other method of escaping double quotes I found on Stack Overflow, and it appears only the first one is actually being escaped for some reason
ForFiles /P C:\Backup /C "CMD /C if NOT #FILE == ^".sync^" echo #FILE"
Can anyone give me some advice on howq to acocomplish this? Thanks!

ForFiles /P u:\Backup /C "CMD /C echo #FILE|find /v /i "".sync"""
worked for me, using my u: drive. No doubt it would also filter out *.sync* - if that's or any concern.

I understand that you simply want to list all the dirs under C:\Backup except the .sync one, am I right? Here's the code to do it:
dir /ad /b C:\Backup | find /V ".sync"

To escape the double-quotes within the command after the /C switch of forfiles, you have got two possibilities:
forfiles /P "C:\Backup" /C "CMD /C if #isdir==TRUE if /I not #file==\".sync\" echo #file"
forfiles /P "C:\Backup" /C "CMD /C if #isdir==TRUE if /I not #file==0x22.sync0x22 echo #file"
The first variant is perhaps more obvious, but poorly documented.
The second variant uses the hexadecimal character code of ". Although this might be more difficult to read, I recommend this method, because this hides the nested quotes from the command interpreter cmd; the \" variant might confuse cmd as the \ escaping applies to forfiles but not to cmd, so it recognises the ".
I stringly recommend to add the switch /I to the if command to do the comparison of file/directory paths in a case-insensitive manner, because Windows does not care about the case in paths.
As you can see I have inserted another if statement: I preceded the entire command line with if #isdir==TRUE, to filter out all files, as you are trying to output a list of folders (directories) only.

Related

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

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 /?.

How to add fake blanks in batch file

i've copied from an else author from here the following line:
forfiles /P "C:\SomePath" /S /M test.txt /C "cmd /c if #ftime LSS %new_time% del /F /Q #path"
I've edited it for my purpose as an e-amil info system:
forfiles /P "C:\screenshots" /S /M "2_screenshot.jpg" /C "cmd /c if #ftime LSS %new_time% bmail -s smtpserver -t me#mail.com -f screenshot#mail.com -a TV 2 got a problem"
So, and here is my problem. When I've send it like this I only get a mail with "TV" as subject. When I am going to include the mail text into "" it will stop there. When I am going to add the command from bmail till problem into () it won't work as well.
Is there any workaround possible or is it possible to add some fake blanks in the text? In html I know %20 for this purpose.
forfiles seems to have an own parser, which makes it neccessary to escape the quotes. The standard way of escaping ^" does not work, with forfiles we need to give it three quotes to remain a single one.
forfiles /P "C:\screenshots" /S /M "2_screenshot.jpg" /C "cmd /c echo """TV 2 got a problem""""
(yes, it looks ugly...)

How to get rid of enclosing double-quotes in the expanded `forfiles` variables?

The forfiles command establishes several variables, indicated by a leading #, which return data concerning the currently iterated item to the loop body.
All the variables related to the path and name of the iterated item return the value enclosed in "". Those are: #file, #fname, #ext, #path and #relpath.
So: how can you get rid of the enclosing double-quotes?
For example, the following code returns relative paths to text files in the given root directory:
forfiles /P "C:\root" /M "*.txt" /C "cmd /C echo #relpath"
Assuming that C:\root contains two files file1.txt and file2.txt, the output will be:
".\file1.txt"
".\file2.txt"
However, I want the list of files without the surrounding "".
I am working on Windows 7 64-bit.
One approach is to nest a for %I loop within the forfiles and use the %~I expansion -- use this code in a Command Prompt window:
forfiles /P "C:\root" /M "*.txt" /C "cmd /Q /C for %I in (#relpath) do echo %~I"
To use that code within a batch file you must double the %-signs:
forfiles /P "C:\root" /M "*.txt" /C "cmd /Q /C for %%I in (#relpath) do echo %%~I"
The returned list of files will be (relying on the sample files from the original question):
.\file1.txt
.\file2.txt
Another variant is to nest another forfiles in the body of the initial one, because forfiles removes (non-escaped) double-quotes within given strings like the command line after /C:
forfiles /P "C:\root" /M "*.txt" /C "cmd /C forfiles /P #path\.. /M #file /C \"cmd /C echo #relpath\""
Or alternatively (the doubled inner forfiles is intentional, this works around a bug -- see this post):
forfiles /P "C:\root" /M "*.txt" /C "forfiles forfiles /P #path\.. /M #file /C \"cmd /C echo #relpath\""
The inner forfiles will enumerate exactly one item, which is the one passed over by the outer loop. Since #relpath is already expanded when the inner loop is executed, the quotes are removed as they are not escaped.
So the returned list of files looks like (again taking the sample files from the original question):
.\file1.txt
.\file2.txt
The additional line-break between the lines is generated by forfiles. You can avoid that using redirection (dismiss forfiles output, but display only the echo output in the console window):
> nul forfiles /P "C:\root" /M "*.txt" /C "cmd /C forfiles /P #path\.. /M #file /C 0x22cmd /C > con echo #relpath0x22"
I remove the quotes like this:
#ECHO OFF
GOTO START
usage:
script.bat "*.txt" "c:\Documents"
script.bat "*.txt"
script.bat
If no arguments added it will crawl the current directory with wildcard mask (*)
Avoid root directory (c:\) because too many sub directories for the output console.
:START
IF "%~2"=="" (SET "_FD=%CD%") ELSE (SET "_FD=%~2")
IF "%~1"=="" (SET "_MA=*") ELSE (SET "_MA=%~1")
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "usebackq delims=" %%A in (
`forfiles /p %_FD% /s /m %_MA% /C "cmd /c ECHO #relpath"`
) DO (
SET "myfile=%%~A"
ECHO !myfile:~2!
)
ENDLOCAL
GOTO :EOF
results:
thumbnails\A0-1.jpg
thumbnails\new folder\img.jpg

How to escape the `#` variable replacement in `forfiles`?

I am using a forfiles command line like this (Windows 7 x64):
forfiles /P "C:\root" /M "*.txt" /C "cmd /C echo #relpath"
How can I escape the replacement of #relpath (relative path to currently iterated item) to get #relpath output literally? (...or any other # variable?)
So far I tried the following things, without success:
\: the # seems to be handled before \ so \#relpath does not work, rather the expanded output is just preceded with \;
^: stating ^# does not show any effect except that the ^ disappears; writing ^^# does not help eigher, one ^ remains in the expanded output then;
0xHH: surprisingly (to me), the forfiles-specific replacement of hexacecimal numbers 0x40 does not work either, it seems that this is done prior to variable parsing;
##: doubling the # keeps the first # literally, that is it;
You could use a delayed expansion
forfiles /P "C:\temp" /M "st*.txt" /C "cmd /v:on /C set r=0x40 & echo !r:~0,1!relpath"
Or you can use percent expansion.
set percent=%
set at=#
forfiles /P "C:\temp" /M "st*.txt" /C "cmd /C echo %percent%at%percent%relpath"
I just found an even easier method:
forfiles /P "C:\root" /M "*.txt" /C "cmd /C echo #^relpath"
Note the ^ after the # sign.

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