Check folder is empty using batch command? - windows

for /F %%i in ('dir /b "C:\Program Files\Apache folder\*.*"') do (
echo Folder is NON empty
goto launch_app
)
How to check a folder is empty?
I tried above command, but it didn't work.

try this:
for /F %%i in ('dir /b /a "C:\Program Files\Apache folder\*"') do (
echo if you see this the folder is NOT empty
goto launch_app
)

File Not Found
#for /f "tokens=*" %%a in ('dir /b /a-d "C:\Progra~1\Apache"') do #...
The error that you see when you run this command, comes for the standard error output. But that is only a warning printed to your console. When this case happens, the body of the iteration won't be evaluated, and the algorithm based on this "for/dir" instruction, is in fact correct.
Now, if you want to get rid of this ugly error message, you need to add the following to your script, in order to redirect the standard error to null device:
2>NUL
so for instance, in a batch file, with the appropriate escape character:
#rem Print a list of file paths
#for /f "tokens=*" %%a in ('dir /b /a-d "%srcPath%" 2^>NUL') do #echo(%srcPath%\%%a

#echo off
cls
echo.
echo.
echo.
echo TEST FOR EMPTY DIRECTORY
echo was tested with "&" without a file
echo.
echo Can use Full or Subfolder path
echo (as below) of where test.bat
echo.
set p=Raw\
echo.
echo Just to show p is set
echo.
echo "p=%p%"
echo.
echo.
echo.
pause
for /F %%i in ('dir /b /a "%p%*"') do (
echo Folder %p% was NOT empty
goto :process
)
echo Folder %p% was empty
:process
echo "BLAH, BLAH, BLAH "
:end
pause
exit
rem Copy past in notepad to try. "Create and use or change the "raw" to your own fancy."
rem Hope this helps. Works great for me and I use it.
rem Have Fun.
rem Note use go to end next line after was empty. Worked great in w10. (this program hmm)
rem IF IT WORKS FOR YOU . GIVE A +. THX!

I wasn't satisfied with the given answers because I try to avoid for loops, goto and temp files whenever I can.
To check if the folder is empty:
dir /b /s /a "C:\Program Files\Apache folder\" | findstr .>nul || (
echo Folder is empty
)
To check if folder is not empty:
dir /b /s /a "C:\Program Files\Apache folder\" | findstr .>nul && (
echo Folder is NOT empty
)

dir C:\TEST\*.* /a/b/d/od>C:\TEMP\CHECKFOLDER
for /R C:\TEMP\ %%? in (CHECKFOLDER) do (
if "%%~z?"=="0" (
ECHO Folder is empty.
) ELSE (
ECHO Folder is NOT empty
)
)

Related

Write a script to recursively list directories and files within it in Batch script

I am trying to write a batch script that recursively lists all directories and their files with *.js type in the below format:
For example, if I start with the C:\project directory
c:\project
project.js
project_time.js
c:\project\core
core.js
core_render.js
core_application.js
I tried to implement the above logic in code as follows:
#echo off
for /r %%f in (*.js) do (
echo %%f >> names.txt
)
pause
I was not able to print the directory under which the files are listed.
#echo off
setlocal disabledelayedexpansion
set "lastdir="
( for /r %%A in (*.js) do (
set "nextdir=%%~dpA"
setlocal enabledelayedexpansion
if /i not "!lastdir!" == "!nextdir!" (
rem Empty line and directory path.
if defined lastdir #echo(
#echo !nextdir!
)
endlocal
rem Filename.
#echo %%~nxA
set "lastdir=%%~dpA"
)
) > "names.txt"
The lastdir variable is to record the last directory path so it is echoed only once.
If lastdir is different to %%~dpA:
If lastdir is defined, then an empty line will be echoed.
Directory path of found file is echoed.
Filename is always echoed.
for modifiers dp is the drive and path. nx is the name and extension.
setlocal enabledelayedexpansion is used only where needed so paths with ! are not vulnerable.
I am not going to suggest a command line solution as it would be very long. Instead suggest use of tree command if the output format is suitable.
Here's an untested example, (I'm not expecting it to be quick if your base directory is large):
#Echo Off
(
For /F "Delims=" %%G In ('Dir /B /S /A:D "C:\Project" 2^> NUL') Do (
%__AppDir__%where.exe /Q "%%G":*.js 1> NUL 2> NUL
If Not ErrorLevel 1 (
Echo/
Echo %%G
For /F "EOL=| Delims=" %%H In ('%__AppDir__%where.exe "%%G":*.js')Do (
Echo %%~nxH
)
)
)
) 1> "names.txt"
Pause
If you prefer to run something from the Command Prompt, then try this version:
(For /F "Delims=" %G In ('Dir /B/S/AD "C:\Project" 2^>NUL')Do #(%__AppDir__%where.exe /Q "%G":*.js >NUL 2>&1&&(Echo/&Echo %G&For /F "EOL=|Delims=" %H In ('%__AppDir__%where.exe "%G":*.js')Do #Echo %~nxH)))>"names.txt"
Two simple ways to do this:
dir /S *.js
You get the answers, just as you requested.
FORFILES /S /M *.js /C "cmd /c echo #path"
You get complete path for every file.

FINDSTR: help understanding results. Returns nothing, but no error when there is one expected?

I am writing a batch file. part of the program will compare the list of files in a 'source' folder. With the contents of a list in a text file.
I loop through each file in the folder, and search for its filename in the text file using FINDSTR
Everything works until there is a filename in the source folder that doesnt exist in the text file.
the findstr code:
for /f %%o in ('findstr %name% old.txt') do (
echo o=%%o >> result.txt
if %%o==%name% (
echo %name% exists
) ELSE (
echo %name% does not exists
)
)
Again, the problem occurs when FINDSTR searches for a filename that is not in the text file.
when it reaches that point it outputs the variable %%o as being '%o' and echos nothing. So it sends nothing to the results.txt.
This doesnt trigger an ERRORLEVEL change but also will not echo anything. I have tried outputing the errorlevels but they are also empty. I just dont understand what FINDSTR is doing in this instance.
the FULL batch file: (its my first one. forgive any mistakes)
::return the raw (/b) list of files
FORFILES /p %~dp0source\ /s /m "*.cr2" /C "cmd /c echo #path" > new.txt
::pull file path for each file and send to subroutine
for /f %%n in ('FORFILES /p %~dp0source\ /s /m "*.cr2" /C "cmd /c echo #path"') do (
call :dequote %%n
)
::subroutine for removing quotes
::and returning the filename, extension, and path
:dequote
set fullPath=%~f1
set fileName=%~n1
set fileExt=%~x1
set filePath=%~dp1
set name=%fileName%& set npath=%filePath%& set ext=%fileExt%& set fpath=%fullPath%
echo %fpath%
echo %npath%
echo %name%
echo %ext%
for /f %%o in ('findstr %name% old.txt') do (
echo o=%%o >> result.txt
if %%o==%name% (
echo %name% exists
) ELSE (
echo %name% does not exists
)
)
This only happens on the last filename sent to findstr. Any suggestions or direction would be very appreciated. Ive tried and read everything I can get my hands on.
Thank You for your time.
UPDATE: 9-9-15
Here is the working final batch file i created using the help on this page. It creates a hotfolder that will edit any new files added to it until you stop the script from running:
:start
:: return the raw (/b) list of files and full path to source text
FORFILES /p %~dp0source\ /s /m "*.cr2" /C "cmd /c echo #path" > source.txt
IF %ERRORLEVEL% EQU 1 goto :start
::join new and old data, return only what is shared in common (/g)
findstr /I /L /G:"source.txt" "output.txt" > found.txt
IF %ERRORLEVEL% EQU 1 copy /y source.txt notFound.txt
::join found file names and source filenames, return those that do not have a match
findstr /I /L /V /G:"found.txt" "source.txt" >> notFound.txt
IF %ERRORLEVEL% EQU 2 echo error no match
::for each line of notFound.txt, dequote and break apart
for /f %%n in (notFound.txt) do (
echo n=%%n
call :dequote %%n
)
:dequote
set fullPath=%~f1
set fileName=%~n1
set fileExt=%~x1
set filePath=%~dp1
set name=%fileName%& set npath=%filePath%& set ext=%fileExt%& set fpath=%fullPath%
echo %fpath%
echo %npath%
echo %name%
echo %ext%
cd %nPath%
if NOT [%1]==[] (
echo converted %name%
convert -negate -density 600 -colorspace gray flatField.cr2 %name%%ext% -compose Divide -composite %name%.tif
move %name%.tif %~dp0output
cd %~dp0
del notFound.txt
copy /y source.txt output.txt
) ELSE (
echo end of batch else
cd %~dp0
)
Loop variables must be referenced with %% in a batch file because percent sign has a special meaning and must be therefore escaped with another percent sign in a batch file to specify it literally. This is the reason why on running the batch file with echo on in a command prompt window results in getting %%o in the batch file displayed as %o on execution.
Command FOR as used in
for /f %%o in ('findstr %name% old.txt') do
processes the output written to stdout by the called command findstr. But findstr does not write anything to standard output when it searched for one or more strings in a file and could not find any matching string in any line of the file.
So command for can't process anything and therefore none of the commands after do are processed at all in this case.
Assuming the list file contains only file names without path, the following commented batch file can be used to get with 1 execution of command dir and just 1 or 2 executions of console application findstr the two lists containing the file names in folder being found and being not found in the list file. The batch file is written for not producing empty files.
#echo off
setlocal
set "ListFile=C:\Temp\List.txt"
if not exist "%ListFile%" goto NoListFile
set "SourceFolder=C:\Temp\Test"
if not exist "%SourceFolder%\*" goto NoSourceFolder
set "AllFileNames=%TEMP%\AllFileNames.txt"
set "FoundFileNames=%TEMP%\FoundFileNames.txt"
set "NotFoundFileNames=%TEMP%\NotFoundFileNames.txt"
rem Get alphabetic list of files in source folder without path.
dir /A /B /ON "%SourceFolder%" >"%AllFileNames%"
rem Find all file names in list file with a case-insensitive
rem search matching completely a file name in list file and
rem output the found file names to another list file.
%SystemRoot%\system32\findstr.exe /I /L /X "/G:%AllFileNames%" "%ListFile%" >"%FoundFileNames%"
if errorlevel 1 goto NoFileNameFound
rem Find all file names with a case-insensitive search found
rem before in all file names list and output the lines not
rem containing one of the file names to one more list file.
%SystemRoot%\system32\findstr.exe /I /L /V "/G:%FoundFileNames%" "%AllFileNames%" >"%NotFoundFileNames%"
if errorlevel 1 goto AllFileNamesFound
rem Some file names are found in list file and others not.
del "%AllFileNames%"
goto :EndBatch
:NoFileNameFound
move /Y "%AllFileNames%" "%NotFoundFileNames%"
del "%FoundFileNames%"
goto EndBatch
:AllFileNamesFound
del "%AllFileNames%"
del "%NotFoundFileNames%"
goto EndBatch
:NoListFile
echo %~f0:
echo Error: No list file %ListFile%
goto EndBatch
:NoSourceFolder
echo %~f0:
echo Error: No folder %SourceFolder%
:EndBatch
endlocal
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
del /?
dir /?
findstr /?
goto /?
if /?
move /?
set /?
This is a method to give you a list of filenames which don't exist in the file.txt
#echo off
cd /d "c:\folder\to\check"
for %%a in (*) do findstr /i "%%~nxa" "file.txt" >nul || echo "%%a" is missing
pause
It uses %%~nxa instead of %%a in case subdirectories are used at some point.

Batch remove parenthesis from file name

After successfully removing a bunch of Google Drive Folder duplicates, some files retain a "filename(2)"name.
Is there a way to batch rename every file so the parenthesis and the number inside the parenthesis is gone?
That includes folders and sub-folders.
Try like this :
Create a file test.bat with the code below in it and replace the path to test in the var $path
#echo off
set $path="C:\Users\CN Micros\Desktop\PROGRAMMATION\test"
for /f "tokens=1-3 delims=^(^)" %%a in ('dir /b/a-d %$path%') do (
if exist %$path%\"%%a(%%b)%%c" echo ren %$path%\"%%a(%%b)%%c" "%%a%%c"
)
pause
Then run it in the CMD or by double clicking.
If the output is ok for you remove the echo
The program create 3 tokens : %%a = what's before the (), %%b What's inside the () and %%c what's after the ().
Then we arrange this 3 tokens to rename the files without the ().
If you have some file who have the same final name ie : "file(1)name", "file(2)name" --> "filename"
It will work only with the first one. If you have this case you have to add a counter at the end of file to be sure that they will be renamed.
This will create renfiles.bat.txt for you to examine in Notepad and then rename to .bat and execute if you are happy with it.
#echo off
dir /b /a-d *(*).* |find /i /v "%~nx0" |find /i /v "repl.bat" |repl "(.*)\(.*\)(\..*)" "ren \q$&\q \q$1$2\q" xa >"renfiles.bat.txt"
This uses a helper batch file called repl.bat - download from: https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat
Place repl.bat in the same folder as the batch file or in a folder that is on the path.
Edit: This version will recurse through subdirectories:
#echo off
dir /b /s /a-d *(*).* |find /i /v "%~nx0" |find /i /v "repl.bat" |repl ".*\\(.*)\(.*\)(\..*)" "ren \q$&\q \q$1$2\q" xa >"renfiles.bat.txt"
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR /f "delims=" %%a IN (
'dir /b /s /a-d "%sourcedir%\*" '
) DO (
SET "name=%%~na"
SETLOCAL ENABLEDELAYEDEXPANSION
SET "newname=!name:)=!"
SET "newname=!newname:(=!"
IF "!name!" neq "!newname!" (
IF EXIST "%%~dpa!newname!%%~xa" (ECHO cannot RENAME %%a
) ELSE (ECHO(REN "%%a" "!newname!%%~xa")
)
endlocal
)
GOTO :EOF
You'd need to set your required directory into sourcedir. I used u:\sourcedir which suits my testing.
The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(REN to REN to actually rename the files.

For Loop in Batch File Renames One File Twice

I wrote this batch file to append some text to the filenames of a set of jpeg files, giving the option to append them before or after the current filename.
But for some odd reason when appending before the filename, one file is being proccessed twice getting the result as new_new_FileName.jpg while all other files are getting just new_FileName.jpg.
Interesting enough, this problem isn't happening always, as well as when appending after the filename it is always working fine.
Following is the entire code, with no visual difference between the before or after, but still resulting differently. Can anyone please examine this file and explain me where I'm wrong?
Help is appreciated.
#ECHO off
title Rename Script
set /A count=1
:Start
cls
set /p STR=choose a string to append:
cls
echo 1. Append before
echo 2. Append after
set /p choice=I choose (1,2):
if %choice%==1 goto renameb
if %choice%==2 goto renamea
:renameB
cls
echo Appending '%STR%' before current file name.
echo.
set /A count=0
FOR %%a in (*.jpg) DO (
ren "%%~a" "%STR%%%~na%%~xa"
echo Was: %%~a Became: %STR%%%~na%%~xa
set /A count+=1
)
goto end
:renameA
cls
echo Appending '%STR%' after current file name.
echo.
set /A count=0
FOR %%a in (*.jpg) DO (
ren "%%~a" "%%~na%STR%%%~xa"
echo Was: %%~a Became: %%~na%STR%%%~xa
set /A count+=1
)
goto end
:end
echo[
echo %count% files were renamed.
echo[
echo The process in now done.
pause
for renaming, the simple for loop doesn't work:
FOR %%a in (*.jpg) DO (
for some reasons from the old CP/M days with the FCB's a for /f loop is needed:
for /f "delims=" %%a in ('dir /a-d /b *.jpg') do (

Skip when error occurs

i have the following code in batch (cmd):
for /f "delims=" %%f in ('dir /b /s Example') do (
command
if %errorlevel%==1 (
command
SKIP
)
command
)
EDIT:
To make things more clear:
for /f... searches for a directory called 'Example' and loops to search for more directories than one.
the first command is a delete command, it deletes all files in the directory.
the command that happens when an error occurs, is a echo command which writes some info about the error to a text file.
now the hole skip thing; sometimes, the files can't be deleted because of access denied or this file is in use by.... Normally, what would happen if there weren't a skip thing, it would just stop the command and hang. So, what i want to do, is prevent this from happening. Alternatively, i want to use something like skip, so it can skip the file and continue anyways. So i think this command needs to be piped in the delete command.
I hope it's clear now.
Thanks in advance.
Like this?
for /f "delims=" %%f in ('dir /b /s Example') do (
command
if not errorlevel 1 (
command-for-success
) else (
command-for-error
)
)
Create the two command files and run delex.cmd. The files and directories that are not deleted will be logged to delex.txt. The ones that hang, will have a minimized cmd window open that gets killed after a delay by using ping (thanks to Doc Brown's suggestion).
delex2.cmd
----------
#echo off
del /q %1
if exist %1 echo %1 not deleted!>>delex.txt
exit
delex.cmd
---------
#echo off
if exist delex.txt del delex.txt
for /f "delims=" %%f in ('dir /s /b example') do start "delextaskkill" /min delex2.cmd "%%f"
ping 127.0.0.1 -n 3 -w 1000> nul
taskkill /fi "Windowtitle eq delextaskkill"> nul
Tested with:
\example
| file1
| file2
| file3
| file4
| file5
|
\---example
file1
file2
file3
file4
file5
When one uses del, and "access denied" or "this file is in use by..." occurs, %errorlevel% is 0, so testing %errolevel% is useless. Perhaps the following simple solution works in your case:
for /f "delims=" %%f in ('dir /b /s Example') do (
del %%f
if exist %%f (
echo "file not deleted"
) else (
echo "file deleted"
)
)
I believe that this is what you want
for /f "delims=" %%f in ('dir /b /s Example') do (
command
if not errorlevel 1 (
command
) else (
command
goto :eof
)
)
Perhaps this is more advanced than can be accomplished using just built-in cmd processing. Why not consider using the Windows Scripting Host (vbscript/jscript) or even PowerShell? Both will likely provide you the level of control you are requesting.
Try this batch file:
#echo off
REM For each directory named 'Example' ...
for /f "delims=" %%f in ('dir /b /s Example') do (
REM .. enter the directory and delete all the files found there.
pushd .
cd %%f
del /q *
for /f "delims=" %%z in ('dir /b') do (
REM Any files that still exist must have been inaccessable. Log an error.
echo Unable to delete file %%z > C:\logfile.txt
)
popd
)
Tested with the following directory structure:
folder\
|------Example\
| |-------file1 (write-protected)
| |-------file2
| |-------file3
|------deeper\
|-------Example\
|-------file4
|-------file5 (write-protected)
|-------file6
After running the batch file, only file1 and file5 were left. An "Access is denied" message was printed for each write-protected file encountered; if that gets annoying you re-direct the output of the batch file like script.bat > NUL to hide it.
So after all the existing answers didn't satisfy you and you absolutely need a skip within your batch file, i will make another try:
#echo off
setlocal
for /f "delims=" %%f in ('dir /b /s batch') do call :DoSomething %%f
goto end
:DoSomething
echo Here i am: %1
if %errorlevel%==1 goto :eof
echo No error occured
goto :eof
:end
endlocal
The trick is, that the for loop calls a sub function within the same file and gives the needed parameter to it. This new call runs in a new context and can only access the variables which are defined after the do call :DoSomething in the given order their.
So you have to access the variables here with %1, %2, etc. If you want to leave this context you have to make a goto :eof to jump to the end of the file (this marker is predefined in batch mode and should not occur within your file), what leaves the context and returns to the for loop.
After running through the whole loop we just jump to the :end marker, make a little clean up and are finished.
The following looks for the file extentions you want recursively under the "dirname" directory tree and executes commandstuff.bat against that file name:
for /r %i in (c:\dirname\*.ext) do
commandstuff "%i"
Commandstuff.bat looks like this:
#ECHO OFF del %1 IF (%ERRORLEVEL% ==
0) goto END
:ERROR Echo Error deleting %1
:END Echo end
This would run commandstuff.bat for you to delete the files you want. When there is an error it will simply echo the file details and continue processing the next file.

Resources