for loop with if else in a batch - batch-file

I am creating a batch for creation of zip files from folders, I want to check if the zip file has been created succesfully. It does the logging of which zip file has been created but when it goes wrong it should goto a label and stop the operation. This does not work, the ELSE command is echoed and not executed.
SETLOCAL EnableExtensions EnableDelayedExpansion
for /d %%d in (*) do (
"7z.exe" a -r -tzip "%%d.zip" ".\%%d\" & IF %ERRORLEVEL% EQU 0 (echo Archive "%%d.zip" created succesfully >> "Archive-log %date%.txt") ELSE (set fault="%%d.zip" goto createzip))
exit /b
:createzip
echo Failed creating archive %fault% >> "Error-log %date%.txt"
exit /b

Here is the batch code rewritten and extended. The batch file does not immediately stop on failing to compress a subfolder to a ZIP archive.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Get current date in region dependent format with . as delimiter.
set "FileDate=%DATE:/=.%"
set "ErrorCount=0"
set "FolderCount=0"
rem Compress each non hidden subfolder in current folder into a ZIP file.
for /D %%I in (*) do (
set /A FolderCount+=1
"7z.exe" a -r -tzip "%%I.zip" ".\%%I\"
if errorlevel 1 (
echo Failed creating archive: "%%I.zip">>"Error-log %FileDate%.txt"
set /A ErrorCount+=1
) else (
echo Archive "%%I.zip" created succesfully.>>"Archive-log %FileDate%.txt"
)
)
rem Exit batch processing if no subfolder was found in current folder?
if %FolderCount% == 0 endlocal & exit /B
set "ErrorPluralS=s"
if %ErrorCount% == 1 set "ErrorPluralS="
set "FolderPluralS=s"
if %FolderCount% == 1 set "FolderPluralS="
echo Processed %FolderCount% folder%FolderPluralS% with %ErrorCount% error%ErrorPluralS%.>>"Archive-log %FileDate%.txt"
endlocal
if errorlevel 1 working also without usage of delayed expansion means:
IF the exit code of the previous command or executable is greater or equal 1 THEN ...
This is explained in the Microsoft support article Testing for a Specific Error Level in Batch Files and working from MS-DOS to Windows 10 in batch files and on command line.
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.
echo /?
endlocal /?
for /?
if /?
rem /?
set /?
setlocal /?
Read also the answers on:
Single line with multiple commands using Windows batch file
How to get information about current path %CD% in batch in a FOR loop?

I think it's because your ELSE contains 2 statements which aren't separated so the goto ends up being part of the set command. To fix that and for readability, I think you should reformat a bit:
for /d %%d in (*) do (
"7z.exe" a -r -tzip "%%d.zip" ".\%%d\"
IF %ERRORLEVEL% EQU 0 (
echo Archive "%%d.zip" created succesfully >> "Archive-log %date%.txt"
) ELSE (
set fault="%%d.zip"
goto createzip
)
)

Related

Can't pass correctly the parameters of batch script into a command inside a loop statement

I have a problem with passing parameters to commands inside the script which downloads online stream to individual directory and then fixes errors using ffmpeg.
First I check if directory exists and if not then create one:
if exist %1 (
echo Directory exists
) ELSE (
mkdir "%1%"
echo Directory created
)
And then there is a main loop which tries to download the stream and fix errors in it.
for /L %%C in (1,1,10000) do (
streamlink -o "%%1\%%1%%C.mp4" "some.url/%2" best
if exist %1\%1%C.mp4 (
d:\streamlink\ffmpeg\bin\ffmpeg.exe -loglevel debug -i "%1\%1%C.mp4" -c:v copy -c:a copy "%1\%1%C_o.mp4" 1>"%1%\log\%1%%C.log" 2>"%1%\err\%1%%C.err"
)
timeout /T 300
)
So for example if I execute:
script.cmd foo xyz
then in first loop should be executed:
streamlink -o "foo\foo1.mp4" "some.url/xyz" best
if exist foo\foo1.mp4 (
d:\streamlink\ffmpeg\bin\ffmpeg.exe -loglevel debug -i "foo\foo1.mp4" -c:v copy -c:a copy "foo\foo1_o.mp4" 1>"foo\log\foo1.log" 2>"foo\err\foo1.err"
)
Could you help me with this?
Please open a command prompt, run call /? and read the output help explaining how arguments of a batch file can be referenced from within a batch file. Argument 0 is the batch file currently processed by cmd.exe.
I suggest this batch file for the task although not knowing what the FOR loop really does.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
if "%~1" == "" (
echo ERROR: %~nx0 must be called with a directory path as first argument.
goto EndBatch
)
if "%~2" == "" (
echo ERROR: %~nx0 must be called with ??? as second argument.
goto EndBatch
)
rem Assign the directory path to an environment variable.
set "DirectoryPath=%~1"
rem Make sure the directory path contains \ and not / as directory separator.
set "DirectoryPath=%DirectoryPath:/=\%"
rem Make sure the directory path ends with a backslash.
if not "%DirectoryPath:~-1%" == "\" set "DirectoryPath=%DirectoryPath%\"
rem Check if the directory exists already and create it otherwise.
if exist "%DirectoryPath%" (
echo Directory exists.
) else (
md "%DirectoryPath%"
if exist "%DirectoryPath%" (
echo Directory created.
) else (
echo ERROR: %~nx0 failed to create directory "%DirectoryPath:~0,-1%"
goto EndBatch
)
)
rem Get name of last directory from directory path for the various file names.
for %%I in ("%DirectoryPath:~0,-1%") do (
set "VideoFileName=%DirectoryPath%%%~nxI"
set "StdLogFileName=%DirectoryPath%log\%%~nxI
set "ErrLogFileName=%DirectoryPath%err\%%~nxI
)
rem Create the two additional subdirectories with suppressing the
rem error messages output on these directories existing already.
md "%DirectoryPath%log" 2>nul
md "%DirectoryPath%err" 2>nul
for /L %%I in (1,1,10000) do (
streamlink.exe -o "%VideoFileName%%%I.mp4" "some.url/%~2" best
if not errorlevel 1 if exist "%VideoFileName%%%I.mp4" (
"D:\streamlink\ffmpeg\bin\ffmpeg.exe" -loglevel debug -i "%VideoFileName%%%I.mp4" -c:v copy -c:a copy "%VideoFileName%%%I_o.mp4" >"%StdLogFileName%%%I.log" 2>"%ErrLogFileName%%%I.log"
)
rem Don't know what this wait is for.
%SystemRoot%\Sytem32\timeout.exe /T 300
)
rem Remove all empty standard log files.
for %%I in ("%StdLogFileName%*.log") do if %%~zI == 0 del "%%I"
rem Remove the standard log file directory on being empty now.
rd "%DirectoryPath%log" 2>nul
rem Remove all empty error log files.
for %%I in ("%ErrLogFileName%*.log") do if %%~zI == 0 del "%%I"
rem Remove the error log file directory on being empty now.
rd "%DirectoryPath%err" 2>nul
:EndBatch
echo/
endlocal
pause
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 /?
goto /?
if /?
md /?
pause /?
rd /?
rem /?
set /?
setlocal /?
timeout /?
See also:
Microsoft article about Using command redirection operators
DosTips forum topic: ECHO. FAILS to give text or blank line - Instead use ECHO/

batch script - find and replace line that starts with specific value in an .ini file

Hello and firstly I would like to apologize for this post if it was already answered before. I spent the last 4 hours searching Stackoverflow and Google.
I have a gamesettings.ini file I would like to edit via batch file. I need to perform this over many PCs, so I would like to keep the other settings besides 2 lines in the file.
The two lines im trying to change are:
CustomVoiceChatInputDevice=Default Input
CustomVoiceChatOutputDevice=Default Output
I tried a few batch scripts I found on Stackoverflow, but they only work if I define the full line. Since every user has different options set, i need the script to just take the start of the line. Just "CustomVoiceChatInputDevice" for example.
Here's an example code I used, thanks to #jsanchez. This script doesn't work unless I type out the whole line:
Thank you for your time!!
#echo off
::Use the path from whence the script was executed as
::the Current Working Directory
set CWD=C:\
::***BEGIN MODIFY BLOCK***
::The variables below should be modified to the
::files to be changed and the strings to find/replace
::Include trailing backslash in _FilePath
set _FilePath=C:\Users\NEOSTORM\AppData\Local\RedDeadGame\Saved\Config\WindowsClient\
set _FileName=GameUserSettings.ini
::_WrkFile is the file on which the script will make
::modifications.
set _WrkFile=GameUserSettings.bak
set OldStr="CustomVoiceChatInputDevice"
set NewStr="CustomVoiceChatInputDevice=Line (Astro MixAmp Pro Game)"
::***END MODIFY BLOCK***
::Set a variable which is used by the
::search and replace section to let us
::know if the string to be modified was
::found or not.
set _Found=Not found
SETLOCAL
SETLOCAL ENABLEDELAYEDEXPANSION
if not exist "%_FilePath%%_FileName%" goto :NotFound
::If a backup file exists, delete it
if exist "%_FilePath%%_WrkFile%" (
echo Deleting "%_FilePath%%_WrkFile%"
del "%_FilePath%%_WrkFile%" >nul 2>&1
)
echo.
echo Backing up "%_FilePath%%_FileName%"...
copy "%_FilePath%%_FileName%" "%_FilePath%%_WrkFile%" /v
::Delete the original file. No worries, we got a backup.
if exist "%_FilePath%%_FileName%" del "%_FilePath%%_FileName%"
echo.
echo Searching for %OldStr% string...
echo.
for /f "usebackq tokens=*" %%a in ("%_FilePath%%_WrkFile%") do (
set _LineChk=%%a
if "!_LineChk!"==%OldStr% (
SET _Found=Found
SET NewStr=!NewStr:^"=!
echo !NewStr!
) else (echo %%a)
)>>"%_FilePath%%_FileName%" 2>&1
::If we didn't find the string, rename the backup file to the original file name
::Otherwise, delete the _WorkFile as we re-created the original file when the
::string was found and replaced.
if /i "!_Found!"=="Not found" (echo !_Found! && del "%_FilePath%%_FileName%" && ren "%_FilePath%%_WrkFile%" %_FileName%) else (echo !_Found! && del "%_FilePath%%_WrkFile%")
goto :exit
:NotFound
echo.
echo File "%_FilePath%%_FileName%" missing.
echo Cannot continue...
echo.
:: Pause script for approx. 10 seconds...
PING 127.0.0.1 -n 11 > NUL 2>&1
goto :Exit
:Exit
exit /b
Each setting within your .ini file identifies the name of the setting. So the order of the lines should not may not matter.
If the line order is meaningless, then all you need do is use FINDSTR /V to remove the old values, and then simply append the new values. In the script below I modify both values at the same time.
#echo off
setlocal enableDelayedExpansion
set "iniLoc=C:\Users\NEOSTORM\AppData\Local\RedDeadGame\Saved\Config\WindowsClient"
set "iniFile=%iniLoc%\GameUserSettings.ini"
set "iniBackup=%iniLoc%\GameUserSettings.bak"
set "CustomVoiceChatInputDevice=Line (Astro MixAmp Pro Game)"
set "CustomVoiceChatOutputDevice=Some new value"
>"%iniFile%.new" (
findstr /vb "CustomVoiceChatInputDevice= CustomVoiceChatOutputDevice=" "%iniFile%"
echo CustomVoiceChatInputDevice=!CustomVoiceChatInputDevice!
echo CustomVoiceChatOutputDevice=!CustomVoiceChatOutputDevice!
)
copy "%iniFile%" "%iniBackup%"
ren "%iniFile%.new" *.
It would be slightly faster to create the backup file via rename instead of copy, but then there would be a brief moment where the ini file does not exist.
Windows command processor is not designed for editing text files, it is designed for running commands and applications.
But this text file editing/replacing task can be nevertheless done with cmd.exe (very slow):
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "FileName=%LOCALAPPDATA%\RedDeadGame\Saved\Config\WindowsClient\GameUserSettings.ini"
set "TempFile=%TEMP%\%~n0.tmp"
if not exist "%FileName%" goto EndBatch
del "%TempFile%" 2>nul
for /F delims^=^ eol^= %%A in ('%SystemRoot%\System32\findstr.exe /N "^" "%FileName%"') do (
set "Line=%%A"
setlocal EnableDelayedExpansion
if not "!Line:CustomVoiceChatInputDevice=!" == "!Line!" (
echo CustomVoiceChatInputDevice=Line (Astro MixAmp Pro Game^)
) else if not "!Line:CustomVoiceChatOutputDevice=!" == "!Line!" (
echo CustomVoiceChatOutputDevice=Line (Astro MixAmp Pro Game^)
) else echo(!Line:*:=!
endlocal
) >>"%TempFile%"
rem Is the temporary file not binary equal the existing INI file, then move
rem the temporary file over existing INI file and delete the temporary file
rem if that fails like on INI file currently opened by an application with
rem no shared write access. Delete the temporary file if it is binary equal
rem the existing INI file because of nothing really changed.
%SystemRoot%\System32\fc.exe /B "%TempFile%" "%FileName%" >nul
if errorlevel 1 (
move /Y "%TempFile%" "%FileName%"
if errorlevel 1 del "%TempFile%"
) else del "%TempFile%"
:EndBatch
endlocal
See the answer on How to read and print contents of text file line by line? for an explanation of the FOR loop.
Please note the caret character ^ left to ) in the two lines to output. A closing parenthesis outside a double quoted argument string must be escaped here with ^ as otherwise ) would be interpreted by Windows command processor as end of command block and not as literal character to output by command ECHO. Other characters with special meaning for cmd.exe on parsing a command line or an entire command block like &|<> must be also escaped with ^ on ECHO command lines.
Please take also a look on Wikipedia article about Windows Environment Variables. It is highly recommended to use the right predefined environment variables for folder paths like local application data folder.
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 /? ... explains %~n0 ... batch file name without path and file extension.
del /?
echo /?
endlocal /?
fc /?
findstr /?
for /?
if /?
move /?
rem /?
set /?
setlocal /?

How to create batch file that move files from sub-folder up one level renaming duplicates?

I already have a batch file that I can drop in any SHOW_NAME directory and it will move files from a sub-folder to its SEASON parent directory. For example:
F:\TV_SHOWS\SHOW_NAME\SEASON1\TITLE_EP1\title_episode1.mkv
F:\TV_SHOWS\SHOW_NAME\SEASON1\TITLE_EP2\title_episode2.mkv
F:\TV_SHOWS\SHOW_NAME\SEASON1\TITLE_EP3\title_episode3.mkv
F:\TV_SHOWS\SHOW_NAME\SEASON1\title_episode3.mkv
When it moves all files to the parent folder (SEASON1) the "title_episode3.mkv" is a duplicate and overwrites the original. How can I automatically rename by appending a number "title_episode3 (1).mkv"?
Here is the code that I use in a batch file:
#echo off
for /d /r %%f in (*) do (
for /d %%g in ("%%f\*") do (
for %%h in ("%%~g\*.mkv") do move "%%~h" "%%~f" >nul 2>&1
)
)
Thanks!
This commented batch file can be used for this task:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Search for any file two directory levels below specified directory
rem and pass to subroutine MoveFile the name of the file with full path.
for /D %%A in ("F:\TV_SHOWS\SHOW_NAME\*") do (
for /D %%B in ("%%A\*") do (
for /F "delims=" %%I in ('dir "%%B\*" /A-D /B /S 2^>nul') do call :MoveFile "%%I"
)
)
endlocal
goto :EOF
:MoveFile
set "FilePath=%~dp1"
set "FileNameOnly=%~n1"
set "FileNameFull=%~1"
set "FileName+Ext=%~nx1"
set "FileExtension=%~x1"
rem For files staring with a dot and not containing one more dot.
if "%FileNameOnly%" == "" set "FileNameOnly=%~x1" & set "FileExtension="
rem Get path to parent folder ending with a backslash.
for /F "delims=" %%J in ("%FilePath:~0,-1%") do set "FileParent=%%~dpJ"
rem Uncomment the line below to see the values of the six File* variables.
rem set File & echo/
rem Does a file with current file name not exist in parent folder?
if not exist "%FileParent%%FileName+Ext%" (
rem Move the file to parent folder and if this was successful
rem delete the folder of the moved file if being empty now.
move "%FileNameFull%" "%FileParent%%FileName+Ext%" >nul
if not errorlevel 1 rd "%FilePath%" 2>nul
goto :EOF
)
set "FileNumber=1"
:NextFile
if exist "%FileParent%%FileNameOnly% (%FileNumber%)%FileExtension%" set /A "FileNumber+=1" & goto NextFile
move "%FileNameFull%" "%FileParent%%FileNameOnly% (%FileNumber%)%FileExtension%" >nul
if not errorlevel 1 rd "%FilePath%" 2>nul
goto :EOF
Running the batch file a second time on same directory with no new subdirectory and no new file does not change anything.
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 /?
for /?
goto /?
if /?
move /?
rd /?
rem /?
set /?
setlocal /?
See also:
the Microsoft article about Using Command Redirection Operators;
Single line with multiple commands using Windows batch file;
Where does GOTO :EOF return to?

How to write a batch script to read a text file line by line,match it with a regex and then edit the line in the same file

I am new to batch scripting
I am supposed to write a batch file to read a text file and two command line parameter say ,"task" and "choice".There can be two values for choice-"enable" and "disable"
Now i would want to input the file line by line and match the starting of line with "task" command line argument entered followed by a colon(:) followed by anything .
Now if the choice is "enable" then i have to put ":N" in the respective lines in which the task matches if it doesnt contain a :N already
My text file would contain entries like:
24343:abc:dsd:N
233:zxzxzc
2344:cxzc:xzc
and if i run a command like
myscript.bat 2344 enable
the output of the script should be that the file should be
24343:abc:dsd:N
233:zxzxzc
2344:cxzc:xzc:N
I have been trying to write the code for this for two whole days but still havent been successful.
After all the reading,this is what i have written till now
#echo off
set /A taskname= %1
set choice= %2
FOR /F "tokens=* delims=" %%x in (testdoc.txt) do (
echo %x%|findstr /R "^'%1'.*[^:][^N]$"
if errorlevel 1 (echo does not contain) else (echo contains)
)
In this,i was trying to compare line by line with the regex but it doesnt work as intended.
Any help would be appreciated
Thanks
Regular expression replaces are not possible with pure usage of Windows command line interpreter cmd.exe or the console applications installed with Windows. This would require usage of a scripting language/interpreter with support for regular expression replaces in files like PowerShell or JScript which would be most likely better choices for this task.
However, a pure batch file solution is also possible for this task as it can be seen on commented batch code below with lots of extra features.
#echo off
set "TempFile=
rem Is first parameter /? for getting help?
if "%~1" == "/?" goto ShowHelp
rem Is the batch file not started with any none empty parameter?
if not "%~1" == "" (
rem Does the first parameter not consist of only digits 0-9?
for /F "delims=0123456789" %%I in ("%~1") do goto ShowHelp
)
rem Is there also specified a second parameter?
if not "%~2" == "" (
rem Is the second parameter neither enable nor disable (case-insensitive)?
if /I not "%~2" == "disable" if /I not "%~2" == "enable" goto ShowHelp
)
rem Setup a local environment for this batch file.
setlocal EnableExtensions DisableDelayedExpansion
rem Define the name of the text file without or with path to modify.
rem Define the name of the temporary file needed to modify the file.
set "TextFile=TextFile.txt"
set "TempFile=%TEMP%\%~n0.tmp"
rem Does the text file to modify exist at all?
if not exist "%TextFile%" goto MissingFile
rem Was a task number specified on starting this batch file?
if not "%~1" == "" set "TaskNumber=%~1" & goto FindTask
rem Prompt the user for the task number and make sure that the user really
rem enters a number by verifying user input using a very secure method.
:PromptNumber
set "TaskNumber="
set /P "TaskNumber=Enter task number: "
if not defined TaskNumber goto PromptNumber
setlocal EnableDelayedExpansion
for /F "delims=0123456789" %%I in ("!TaskNumber!") do endlocal & goto PromptNumber
endlocal
:FindTask
rem Does the file to modify contain the number at beginning of a
rem line as specified with first parameter and followed by a colon?
%SystemRoot%\System32\findstr.exe /B /L /M /C:"%TaskNumber%:" "%TextFile%" >nul 2>&1
if errorlevel 1 goto MissingNumber
rem Has the user specified the action to perform as second parameter.
if /I "%~2" == "enable" set "TaskAction=1" & goto ModifyFile
if /I "%~2" == "disable" set "TaskAction=2" & goto ModifyFile
rem Prompt the user for the action to perform.
%SystemRoot%\System32\choice.exe /N /M "Press Y to enable or N to disable task: "
set "TaskAction=%ERRORLEVEL%"
rem Copy the file with ignoring empty lines and lines starting with a
rem semicolon to temporary file with modifying all lines starting with
rem the specified task number according to specified action to perform.
rem But delete the temporary file before if existing by chance.
:ModifyFile
del "%TempFile%" 2>nul
set "FileModified="
for /F "usebackq tokens=1* delims=:" %%I in ("%TextFile%") do (
if not "%%I" == "%TaskNumber%" (
echo %%I:%%J>>"%TempFile%"
) else (
set "TextLine=%%I:%%J"
call :ModifyLine
)
)
rem Was no line modified on copying all the lines to temporary file?
if not defined FileModified del "%TempFile%" & goto EndBatch
rem Move the temporary file over the text file to modify.
move /Y "%TempFile%" "%TextFile%" 2>nul
rem Was the text file overwritten by command MOVE?
if not errorlevel 1 goto EndBatch
rem Inform the user that the text file to modify could not be
rem modified because of being read-only or missing appropriate
rem NTFS permissions or a sharing access violation occurred.
del "%TempFile%"
for /F %%I in ("%TextFile%") do set "TextFile=%%~fI"
echo/
echo ERROR: "%TextFile%" could not be modifed.
echo/
echo Please make sure the file has not read-only attribute
echo set, is not opened in any application and you have
echo the necessary permissions to overwrite this file.
goto HaltBatch
rem This is a subroutine which modifies a line with right task
rem number according to action to perform and outputs this line
rem into the temporary file. It records also if the line needed
rem to be modified at all.
:ModifyLine
if %TaskAction% == 1 (
if not "%TextLine:~-2%" == ":N" (
set "TextLine=%TextLine%:N"
set "FileModified=1"
)
) else (
if "%TextLine:~-2%" == ":N" (
set "TextLine=%TextLine:~0,-2%"
set "FileModified=1"
)
)
>>"%TempFile%" echo %TextLine%
goto :EOF
rem Get name of file with full path which works also for not existing
rem file and inform the user about missing file to modify with full
rem path to see also where this batch file expected it on execution.
:MissingFile
for /F %%I in ("%TextFile%") do set "TextFile=%%~fI"
echo/
echo ERROR: "%TextFile%" does not exist.
goto HaltBatch
:MissingNumber
rem The specified number does not exist in the file to modify
rem at beginning of a line. Inform the user about this error.
echo/
echo ERROR: %TaskNumber% not found in file "%TextFile%".
goto HaltBatch
:ShowHelp
echo/
echo Usage: %~nx0 [task] [disable ^| enable]
echo/
echo task ...... number of the task to enable or disable.
echo disable ... disable the specified task.
echo enable .... enable the specified task.
echo/
echo %~nx0 can be also started without any parameter.
echo In this case the task number and the action to perform
echo can be entered during the execution of the batch file.
:HaltBatch
echo/
pause
echo/
:EndBatch
if defined TempFile endlocal
The command line set "TextFile=TextFile.txt" must be modified to your environment.
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 /?
choice /?
del /?
echo /?
endlocal /?
findstr /?
for /?
goto /?
if /?
move /?
pause /?
rem /?
set /?
setlocal /?
Further read following:
DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/
Microsoft article about Using Command Redirection Operators
Stack Overflow answer on Where does GOTO :EOF return to?
Stack Overflow answer on Single line with multiple commands using Windows batch file

Passing a Variable to Subfolder

I'm a bit stuck here.
Running a batch file that has a couple of steps.
I need to run a batch file in a folder go through each folder and 3 folders down assign that a variable. So copy that 3rd folder down in each folder
So my folder structure
e.g1: 2135698563325\Folder1\Folder2\Folder3\c007
eg2: 21356486543248\Folder1\Folder2\Folder3\c111
REM get c007 as a variable to be able to set a folder name
set variable = Folder0\Folder1\Folder2\Folder3\%Variable%
REM Step 2:Check that the c007 folder doens't already exist
if %Variable%==\\hippo\Folder4\ ((echo "Error: Duplicate Folder"):eof) Else mkdir \\hippo\Folder4\%Variable%
REM Step 3:Copy a default File Structure from Template Dir
xCopy /s \\hippo\production\Folder4\Temaplate \\hippo\production\Folder4\%Variable%
Rem Step 4: Copy the contents of c007 in to Folder6
xCopy /s %Variable% \\hippo\production\Folder4\Variable\Folder5\Folder6\
Does this make more sense?
Here is a comment batch script on how to get c007 and c111. Put your code into the subroutine ProcessFolder. The folder names c007 and c111 are passed to the subroutine via first argument referenced with %~1.
#echo off
setlocal EnableExtensions
rem Get current directory path always without backslash at end. Environment
rem variable CD holds the current directory path usually without backslash
rem at end. But current directory string is with backslash at end if the
rem current directory is the root directory of a drive.
if "%CD:~-1%" == "\" (
set "CurrentFolder=%CD:~0,-1%"
) else (
set "CurrentFolder=%CD%"
)
rem Process the folder names 4 levels below current directory.
for /D %%A in ("%CurrentFolder%\*") do (
for /D %%B in ("%%A\*") do (
for /D %%C in ("%%B\*") do (
for /D %%D in ("%%C\*") do (
for /D %%E in ("%%D\*") do (
call :ProcessFolder "%%~nxE"
)
)
)
)
)
endlocal
rem Avoid a fall through to the subroutine by exiting batch processing here.
goto :EOF
rem Subroutine to process the folder with name found above.
:ProcessFolder
echo Folder variable is: %~1
rem Exit subroutine and continue in the most inner FOR loop above.
goto :EOF
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 /?
for /?
goto /?
if /?
rem /?
set /?
setlocal /?

Resources