Checking if directory exists using batch file - shell

I am trying to use the answer posted in another Stackoverflow post
According to that post, I should be able to use the following batch script to test if a link is a directory
if exist %1\* echo Directory
However, I am not sure how I am supposed to use this.
I have tried replacing
if exist %1\* echo Directory
with
SET "t=%USERPROFILE%\Desktop\testDir"
if exist %t\* echo Directory
But this doesn't echo out Directory like it should (testDir directory exists on my desktop)
Does the %1 in this conext represent something?

I generally use:
if exist %1\. echo Directory
EDIT: Assuming %1 is a directory, the . is a 'file' that is always there, so it's presence ensures it is a directory and not a file.

%1 is the first command line parameter.
C:\Users\User>if exist c:\windows echo windows exist
windows exist
C:\Users\User>if exist c:\windows1 echo windows exist
C:\Users\User>
And a list of some punctuation
& seperates commands on a line.
&& executes this command only if previous command's errorlevel is 0.
|| (not used above) executes this command only if previous command's errorlevel is NOT 0
> output to a file
>> append output to a file
< input from a file
| output of one command into the input of another command
^ escapes any of the above, including itself, if needed to be passed to a program
" parameters with spaces must be enclosed in quotes
+ used with copy to concatinate files. E.G. copy file1+file2 newfile
, used with copy to indicate missing parameters. This updates the files modified date. E.G. copy /b file1,,
%variablename% a inbuilt or user set environmental variable
!variablename! a user set environmental variable expanded at execution time, turned with SelLocal EnableDelayedExpansion command
%<number> (%1) the nth command line parameter passed to a batch file. %0 is the batchfile's name.
%* (%*) the entire command line.
%<a letter> or %%<a letter> (%A or %%A) the variable in a for loop. Single % sign at command prompt and double % sign in a batch file.
And if you want to know if a directory or file.
#Echo off
pushd %1 >nul 2>&1
If errorlevel 0 if not errorlevel 1 Echo %~nx1 is a folder
If errorlevel 1 Echo %~nx1 is not a folder
Popd
If /i "%cmdcmdline:~0,6%"=="cmd /c" pause

Related

Batch: How to set variable in a nested for-loop and re-use it outside of it (enabledelayedexpansion does not work)

I have a batch inside a folder whose goal is to execute all the batch files located in its sub-folders and evaluate their errorlevel. If at least one of them is equal to 1, the main batch will return an exit code equal to 1. This does not mean that the main batch have to exit with the first errorlevel equal to 1: all the sub-batch files must be executed anyway.
EDIT: all the sub-batch files return an exit code equal to 1 if they fail or equal to 0 if they pass (they are all batch files for testing purpose I wrote myself).
Problem: the exit_code variable never changes outside the loops.
I found similar problems here on SO (and a very similar one: Counting in a FOR loop using Windows Batch script) but they didn't help (probably I didn't understand... I don't know, I'm new to batch scripting).
Thanks in advance.
CODE:
#echo off
setlocal enabledelayedexpansion
set exit_code=0
for /D %%s in (.\*) do (
echo ******************** %%~ns ********************
echo.
cd %%s
for %%f in (.\*.bat) do (
echo calling %%f
call %%f
if errorlevel 1 (
set exit_code=1
)
)
echo.
echo.
cd ..
)
echo !exit_code!
exit /B !exit_code!
Let us assume the current directory on starting the main batch file is C:\Temp\Test containing following folders and files:
Development & Test
Development & Test.bat
Hello World!
Hello World!.bat
VersionInfo
VersionInfo.bat
Main.bat
Batch file Development & Test.bat contains just the line:
#dir ..\Development & Test
Batch file Hello World!.bat contains just the line:
#echo Hello World!
Batch file VersionInfo.bat contains just the line:
#ver
Batch file main.bat contains following lines:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
cls
set "exit_code=0"
for /D %%I in ("%~dp0*") do (
echo ******************** %%~nxI ********************
echo/
for %%J in ("%%I\*.bat") do (
echo Calling %%J
echo/
pushd "%%I"
call "%%J"
if errorlevel 1 set "exit_code=1"
popd
)
echo/
echo/
)
echo Exit code is: %exit_code%
endlocal & exit /B %exit_code%
A command prompt is opened in which next the following command lines are executed manually one after the other:
C:\Temp\Test\Main.bat
echo Errorlevel is: %errorlevel%
ren "C:\Temp\Test\Development & Test\Development & Test.bat" "Development & Test.cmd"
C:\Temp\Test\Main.bat
echo Errorlevel is: %errorlevel%
The first execution of Main.bat results in exit with value 1 as it can be seen in command prompt window on the line:
Errorlevel is: 1
The reason is the wrong coded dir command with the directory name not enclosed in double quotes resulting in interpreting Test as command to execute. For that reason the dir command line results in following error output:
Volume in drive C is TEMP
Volume Serial Number is 14F0-265D
Directory of C:\Temp\Test
File Not Found
'Test' is not recognized as an internal or external command,
operable program or batch file.
The exit code of this batch file is not 0 due to the error and for that reason the condition if errorlevel 1 is true and set "exit_code=1" is executed already on first executed batch file.
The processing of the other two batch files always end with 0 as exit code.
The command ren is used to change the file extension of Development & Test.bat to have the batch file next with name Development & Test.cmd resulting in ignoring it by main.bat. The second execution of Main.bat results in exit with 0 as it can be seen on the line:
Errorlevel is: 0
Please read the following pages for the reasons on all the code changes:
Syntax error in one of two almost-identical batch scripts: ")" cannot be processed syntactically here
change directory command cd ..not working in batch file after npm install
DosTips forum topic: ECHO. FAILS to give text or blank line - Instead use ECHO/
Why is no string output with 'echo %var%' after using 'set var = text' on command line?
How does the Windows Command Interpreter (CMD.EXE) parse scripts?
What are the ERRORLEVEL values set by internal cmd.exe commands?
Which cmd.exe internal commands clear the ERRORLEVEL to 0 upon success?
Single line with multiple commands using Windows batch file
Summary of the changes:
Delayed expansion is not enabled in Main.bat as not required here to process also correct directory and file names containing an exclamation mark like C:\Temp\Test\Hello World!\Hello World!.bat.
I and J are used as loop variables instead of s and f because of the latter two letters could be misinterpreted as loop variable modifiers in some cases. Therefore it is better to avoid the letters which have a special meaning for command for on referencing the loop variables.
%~dp0 is used instead of .\ to make sure that the batch file searches for non-hidden subdirectories in the directory of the batch file independent on what is the current directory on starting the batch file. This expression references drive and path of argument 0 which is the full path of currently executed batch file Main.bat. The referenced path of the batch file always ends with a backslash and for that reason %~dp0 is concatenated with * without an additional backslash.
Directory and file name arguments are enclosed in double quotes to work also for names containing a space or one of these characters &()[]{}^=;!'+,`~. %%~nxI and %%J in the two echo command lines are not enclosed in double quotes as not necessary as long as delayed expansion is not enabled. The batch file makes sure that this is not the case for Main.bat.
The usage of "%~dp0*" instead of just .\* in first FOR loop results in getting assigned to loop variable I the directory names with full path never ending with a backslash. The usage of "%%I\*.bat" makes sure to get assigned to loop variable J the full qualified file name of a non-hidden batch file. It is in general better to use full qualified directory/file names wherever possible. This helps also quite often on errors.
The two cd commands are replaced by pushd and popd and moved inside the inner FOR loop. Then it does not matter if a called batch file works only with current directory being the directory of the called batch file or works independent on current directory like Main.bat. Further it does not longer matter if a called batch file changes the current directory as with popd the initial current directory on starting Main.bat is restored as current directory which could be the directory in which files are stored to be processed by the called batch files. The usage of pushd and popd makes this batch file also working on being stored on a network resource and Main.bat is started with its UNC path.
The most important modification is on last command line:
endlocal & exit /B %exit_code%
This command line is first parsed by Windows command processor cmd.exe with replacing %exit_code% by current value of environment variable exit_code defined inside the local environment setup with setlocal EnableExtensions DisableDelayedExpansion. So the command line becomes either
endlocal & exit /B 0
or
endlocal & exit /B 1
Then Windows command processor executes command endlocal to restore the previous environment defined outside Main.bat which results in exit_code no longer defined if not defined in initial execution environment. Then the command exit with option /B to exit just processing of batch file Main.bat is executed with returning 0 or 1 to the parent process which is cmd.exe which assigns the exit code to variable errorlevel.
Well, there is one issue left with the batch file code of Main.bat. A called batch file could modify the value of environment variable exit_code of Main.bat on using the same environment variable without definition of a local environment by using command setlocal. The solution would be to use additionally the commands setlocal before and endlocal after calling a batch file.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
cls
set "exit_code=0"
for /D %%I in ("%~dp0*") do (
echo ******************** %%~nxI ********************
echo/
for %%J in ("%%I\*.bat") do (
echo Calling %%J
echo/
pushd "%%I"
setlocal
call "%%J"
endlocal
if errorlevel 1 set "exit_code=1"
popd
)
echo/
echo/
)
echo Exit code is: %exit_code%
endlocal & exit /B %exit_code%
The command endlocal does not modify errorlevel.
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.
call /?
cls /?
echo /?
endlocal /?
for /?
if /?
popd /?
pushd /?
set /?
setlocal /?

Iterate folder and get filename for commandline input

I am trying to iterate files in a folder and process them with another batch file inside the do loop. It works with echo but as soon as I use the variable as input to the program, it echoes the () part and everything inside.
Here's what I'm trying to do.
#echo off
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
for /r %%f in (/folder/*) do (
set name="%%~nf"
echo !name! <--- ok
process.bat !name! <--- echoes () and commands inside this do loop
)
ENDLOCAL
The process.bat just capitalizes the first letter of the filename and echoes it for debug or confirmation.
A batch file must be called from within a batch file using command call as otherwise Windows command processor continues processing on other batch file with never returning back to initial batch file.
See also: How to call a batch file that is one level up from the current directory?
Please read excellent answer on batch file echo on/off not working properly written by dbenham for the reason on getting suddenly the commands executed by FOR output after first execution of process.bat without using command CALL. I cannot explain better what happens in this case.
The directory separator on Windows is the backslash character \ and not the forward slash / as on Linux or Mac. Windows supports also / in file/folder paths for compatibility reasons by automatically replacing all / by \ before accessing the Windows file systems, but a good written script uses 100% correct syntax and does not depend on automatic corrections done by other programs. / is used on Windows mainly for command line switches.
The usage of / instead of \ can result in an unexpected behavior. For example run a batch file with following content:
#echo off
echo Files in directory %SystemRoot:\=/%/:
for %%I in (%SystemRoot:\=/%/*) echo %%I
echo/
pause
echo/
echo Files in directory %SystemRoot%\:
for %%I in (%SystemRoot%\*) echo %%I
echo/
pause
The first FOR using C:/Windows/* as wildcard pattern outputs the file names with just drive letter + colon + file name + file extension. The file path \Windows\ is missing in output file names. The second FOR loop using C:\Windows\* as wildcard pattern outputs the full qualified file names, i.e. drive letter + colon + file path + file name + file extension.
A file/folder path starting with \ references a directory or file relative to root directory of current DRIVE.
This is explained by the Microsoft documentation Naming Files, Paths, and Namespaces.
It looks like folder is a subdirectory in directory of the executed batch file. In this case / or \ at beginning of folder path is definitely not correct. The backslash at beginning can be omitted or .\ is used to reference the directory folder in current directory on execution of the batch file. But the current directory on batch file execution can be also different to directory containing the executed batch file, for example on running the batch file as administrator, or on running the batch file as scheduled task, or on running the batch file from a network resource accessed using a UNC path. For that reason it is advisable to reference explicitly subdirectory folder in directory of the batch file.
Delayed environment variable expansion is not needed as long as the file name assigned currently to the loop variable does not need to be modified other than the modifiers of for support it. A command line like set name="%%~nf" does not work correct with enabled delayed expansion and file name contains one or more ! because of cmd.exe interprets the exclamation mark(s) in file name as beginning/end of a delayed expanded environment variable reference.
See also: How does the Windows Command Interpreter (CMD.EXE) parse scripts?
It looks like a recursive search for non-hidden files is not really needed as otherwise passing just file name without path and file extension would be not enough to get the right file processed by other batch file process.bat.
So the entire task can be done most likely also with:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
for %%I in ("%~dp0folder\*") do call "%~dp0process.bat" "%%~nI"
endlocal
But if the other batch file process.bat expects that the passed file name without file extension and path is in current directory on execution of process.bat, it is necessary to make the subdirectory folder in directory of this batch file first the current directory.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
pushd "%~dp0folder"
for %%I in (*) do call "%~dp0process.bat" "%%~nI"
popd
endlocal
Note: The batch file folder path referenced with %~dp0 always ends with a backslash. Therefore no additional backslash should be used on concatenating this path string with a file/folder name to avoid having finally on execution of the batch file \\ in full qualified file/folder name, although Windows kernel corrects such paths also automatically by removing second backslash in this case.
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.
call /?
echo /?
endlocal /?
popd /?
pushd /?
set /?
setlocal /?

Batch script to print last line of many files in a folder matching a file name pattern

I have multiple text files in a folder. I would like to print the last line of each file found in the folder matching the file name pattern *.Config and redirect those lines to a new text file.
The below script works for 1 text file. But at the moment I do a for loop for multiple text files and %lastline% prints always the same value.
#echo off & setlocal EnableDelayedExpansion
for /f %%i in ('dir /b *.Config') do (
for /r "delims==" %%a in (%%i) do (
set lastline=%%a
echo %lastline% is the last line of %%i >> vResult.txt
)
)
Use this batch code to get written into file vResult.txt in current directory the last line of each *.config file in current directory:
#echo off
setlocal EnableExtensions EnableDelayedExpansion
del vResult.txt 2>nul
for %%I in (*.config) do (
for /F "usebackq delims=" %%L in ("%%I") do set "LastLine=%%L"
echo !LastLine! is the last line of %%I>>vResult.txt
)
endlocal
First command extensions as needed for the second FOR command line and delayed environment variable expansion as needed for echoing the last line of each file are enabled with second command line. Command extensions are enabled by default, but not delayed expansion.
Then a perhaps already existing vResult.txt is deleted with suppressing the error message output by command DEL to handle STDERR by redirecting it to device NUL in case of the file to delete does not exist.
The outer FOR searches for *.config files in current directory with hidden attribute not set. There is no need to use command DIR here except it would be necessary to find also hidden *.config files.
The inner FOR processes the lines of each *.config file found by the outer FOR loop. It is in general advisable to enclose the file name in double quotes and use usebackq to interpret the double quoted file name as file name and not as string to process in case of a *.config file contains a space character. delims= disables splitting each line up on spaces/tabs to get entire line.
As the environment variable LastLine is defined/modified within a command block, it is necessary to use delayed expansion as enabled at beginning with referencing the environment variable with exclamation marks instead of percent signs.
All environment variables referenced with percent signs of entire command block to execute on each iteration of outer FOR are replaced already by Windows command interpreter with current value of referenced environment variable before executing outer FOR command. This resulted on your batch code with ECHO command line additionally in wrong loop in replacing %lastline% by nothing before the outer FOR is executed the first time.
For debugging a batch file and to see what Windows command interpreter really executes after preprocessing the command lines and the command blocks, remove or comment out #echo off or change that line to #echo on, open a command prompt window, and run the batch file from within this console window by entering its name with full path enclosed in double quotes after changing the current directory to the directory on which the batch file should work.
A space character left of redirection operator >> is also output by command ECHO and therefore also written to the text file as trailing space which is the reason why the space character left of >> is removed here. The space character right of >> would be ignored, but is here also removed.
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 /?
echo /?
endlocal /?
for /?
setlocal /?
set /?
And see also the Microsoft article Using command redirection operators.

Batch file for loop executes on one machine only

I have written the following .bat file, and it runs perfectly on my Windows 2000 machine, but will not run on my Windows 7 or Windows XP machines. Basically it just loops through the current directory and runs a checksum program which returns the checksum. The output of the program is saved to a text file and then formatted to remove the checksum of the output file.
#Echo Off
for /r %%f in (*.txt) do crc32sum.exe %%f >> all_checksums.txt
ren all_checksums.txt old.txt
findstr /v /e /c:"all_checksums.txt" old.txt > all_checksums.txt
del old.txt
When I run this file on my Win2k PC with a bunch of text files and the crc32sum.exe in a folder, it outputs the file. On other machines it outputs a blank file. I turned Echo on and kept only the for loop line and found that the output from executing the crc32sum.exe is nothing. If you manually run the crc32sum.exe file it outputs the checksum no problem.
Any ideas as to how to fix this?
EDIT: Here is a link to the software: http://www.di-mgt.com.au/src/digsum-1.0.1.zip
EDIT2: New development, it seems that the file works if the path of the folder has no spaces in it i.e. C:\temp or C:\inetpub\ftproot or C:\users\admin\Desktop\temp. Does anyone know how I can make this work with paths that have spaces? %%~f doesnt work it says unexpected.
Try this modified batch code which worked on Windows XP SP3 x86:
#echo off
goto CheckOutput
rem Command DEL does not terminate with an exit code greater 0
rem if the deletion of a file failed. Therefore the output to
rem stderr must be evaluated to find out if deletion was
rem successful or (for a single file) the file existence is
rem checked once again. For details read on Stack Overflow
rem the answer http://stackoverflow.com/a/33403497/3074564
rem The deletion of the file was successful if file created
rem from output message has size 0 and therefore the temp
rem file can be deleted and calculation of the CRC32 sums
rem can be started.
:DeleteOutput
del /F "all_checksums.txt" >nul 2>"%TEMP%\DelErrorMessage.tmp"
for %%E in ("%TEMP%\DelErrorMessage.tmp") do set "FileSize=%%~zE"
if "%FileSize%" == "0" (
set "FileSize="
del "%TEMP%\DelErrorMessage.tmp"
goto CalcCRC32
)
set "FileSize="
echo %~nx0: Failed to delete file %CD%\all_checksums.txt
echo.
type "%TEMP%\DelErrorMessage.tmp"
del "%TEMP%\DelErrorMessage.tmp"
echo.
echo Is this file opened in an application?
echo.
set "Retry=N"
set /P "Retry=Retry (N/Y)? "
if /I "%Retry%" == "Y" (
set "Retry="
cls
goto CheckOutput
)
set "Retry="
goto :EOF
:CheckOutput
if exist "all_checksums.txt" goto DeleteOutput
:CalcCRC32
for /R %%F in (*.txt) do (
if /I not "%%F" == "%CD%\all_checksums.txt" (
crc32sum.exe "%%F" >>"all_checksums.txt"
)
)
The output file in current directory is deleted if already existing from a previous run. Extra code is added to verify if deletion was successful and informing the user about a failed deletion with giving the user the possibility to retry after closing the file in an application if that is the reason why deletion failed.
The FOR command searches because of option /R recursive in current directory and all its subdirectories for files with extension txt. The name of each found file with full path always without double quotes is hold in loop variable F for any text file found in current directory or any subdirectory.
The CRC32 sum is calculated by 32-bit console application crc32sum in current directory for all text files found with the exception of the output file all_checksums.txt in current directory. The output of this small application is redirected into file all_checksums.txt with appending the single output line to this file.
It is necessary to enclose the file name with path in double quotes because even with no *.txt file containing a space character or one of the special characters &()[]{}^=;!'+,`~ in its name, the path of the file could contain a space or one of those characters.
For the files
C:\Temp\test 1.txt
C:\Temp\test 2.txt
C:\Temp\test_3.txt
C:\Temp\TEST\123-9.txt
C:\Temp\TEST\abc.txt
C:\Temp\TEST\hello.txt
C:\Temp\TEST\hellon.txt
C:\Temp\Test x\test4.txt
C:\Temp\Test x\test5.txt
the file C:\Temp\all_checksums.txt contains after batch execution:
f44271ac *test 1.txt
624cbdf9 *test 2.txt
7ce469eb *test_3.txt
cbf43926 *123-9.txt
352441c2 *abc.txt
0d4a1185 *hello.txt
38e6c41a *hellon.txt
1b4289fa *test4.txt
f44271ac *test5.txt
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.
cls /?
del /?
echo /?
for /?
goto /?
if /?
rem /?
set /?
type /?
One of the help pages output on running for /? informs about %~I, %~fI, %~dI, %~pI, %~nI, %~xI, %~sI, %~aI, %~tI, %~zI.
Using in a batch file f (in lower case) as loop variable and referencing it with %%~f is a syntax error as command processor expects next the loop variable. %%~ff would be right, but could be different to %%~fI (name of a file/folder with full path and extension without quotes) in comparison to %%~I (string without surrounding quotes).
It is not advisable to use (those) small letters as loop variable. It is better to use upper case letters or character # as loop variable. The loop variable and also those modifiers are case sensitive while nearly everything else in a batch file is case insensitive.

How can I wrap the current directory in strings in CMD?

I need to write a command which will change the current directory and print the NEW directory wrapped in some tags. I thought cd SOMEPATH & echo wkd%cd%wkd would do it but there is a problem.
Here is some example input and output
C:\Users> cd .. & echo wkd%cd%wkd
wkdC:\Userswkd
As you can see, the OLD directory was printed. Why does this happen?
I also tried using newlines (since I feed the command though an external program) but that gives problems when starting command line software.
I really hope there is a solution for this.
In batch files, lines or blocks of code (code enclosed in parenthesis) are first parsed, then executed and the process repeated on the next line/block. During the parse phase all read operations to obtain a value from a variable are removed from the code, replaced with the value in the variable before starting to execute the code.
In your case, when the line is parsed %cd% is replaced with its value before starting to execute the line and change the folder.
Alternatives:
If you separate the command in two lines you will retrieve the correct value.
cd ..
echo wkd%cd%wkd
You can enable delayed expansion and change the syntax used to retrieve the variable from %var% to !var! telling the parser the read operation should be delayed until the execution time
rem inside a batch file
setlocal enabledelayedexpansion
cd .. & echo wkd!cd!wkd
rem from a command line
cmd /v:on /q /c "cd .. & echo wkd!cd!wkd"
You can escape the percent signs to the parser does not see a variable and force a command reevaluation before the echo to get the correct value. You can do it with a call command. It works, but call is slower than other options
rem inside a batch file
cd .. & call echo wkd%%cd%%wkd
rem from command line
cd .. & call echo wkd^%cd^%wkd
Instead of reading a variable, you can execute a command that retrieve the required information
rem from command line
cd .. & for %A in (.) do echo wkd%~fAwkd
cd .. & for /f %A in ('cd') do echo wkd%Awkd
rem in batch files the percent sign needs to be escaped
cd .. & for %%A in (.) do echo wkd%%~fAwkd
cd .. & for /f %%A in ('cd') do echo wkd%%Awkd
(%~fA is the full name of the element referenced by the for replaceable parameter %A)
There is a difference in how for /f and for commands in previous code work
for /f is starting a cmd instance that will execute the cd command to output the current directory, output that is processed by the code in the do clause that is invoked for each output line, with the line stored in the replaceable parameter
for without modifiers directly retrieves a reference to the element indicated, in this case ., the current folder. In this case %~fA is used to obtain a real full name from the relative . reference into an absolute path
All this options are only doing one thing: delay the retrieval of the current folder until the cd .. has been executed.
Give this a try:
cd .. & For /F %A in ('cd') do echo wkd%Awkd
The for loop thing does command output capture as found here: Put command output into a variable
Then I just echo that variable with the stuff around it.
The reason why your original try didn't work is that the %cd% environment variable is set before any of the command executes and is not changed until the interpreter goes on to the next command entirely. It treats foo & bar as a single command with two parts.

Resources