If statement in batch scripting - windows

What I am trying to do is to check if the variable %%c contains a "More" if that is the case insted of a more there should be a "not granted"
#echo off
setlocal EnableDelayedExpansion
for /f "usebackq skip=10 tokens=1,5,9 delims= " %%a in ("log.txt") do (
if %%c == "more"(
set "status" ="Not granted"
)
set "date=%%a"
set "type=%%b"
set "status=%%c"
echo type: !type!
echo status: !status!
echo date: !date!
echo.
)>>Test.txt
pause

Yoru basic questin is: "Does a variable contain a certain string"
In your case (using a for variable), I would use:
echo %%c|find "more">nul && set "status=Not granted"
print the string, pipe it to find (redirecting the ouptut to NUL) and if find was successful, then do something

Related

"ECHO is on" is setting in variable

I have a batch file which takes three parameters [log:path], [logok:path], [logerr:path]. The values of the respective parameter is log:c:\logs\install.log, logok:c:\logs\installok.log,
logerr:c:\logs\installerr.log.
I need to process these 3 parameters and set it on respective variable log=c:\logs\install.log, logok=c:\logs\installok.log, logerr=c:\logs\installerr.log so that I can use them in next step to create a file in those paths.
I have written below script but somehow each variable is printing "ECHO is on". It should actually print the location path. Any idea how to achieve this?
REM PARAMS ARE [LOG:PATH] [LOGOK:PATH] [LOGERR:PATH]
REM ACCESS WITH '%LOG%', '%LOGOK%' AND '%LOGERR%'
REM SETUP LOCALIZED ENVIRONMENT VARIABLES FOR THE LOG, LOGOK AND LOGERR PARAMS
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%A IN (%*) DO (
ECHO %%A >> C:\LOGS\TEST1.TXT
FOR /F "TOKENS=1,2,3 DELIMS=:" %%G IN ("%%A") DO (
SET %%G=%%H:%%I
)
)
ENDLOCAL
ECHO %LOG% >> C:\LOGS\TEST2.TXT
ECHO %LOGOK% >> C:\LOGS\TEST3.TXT
ECHO %LOGERR% >> C:\LOGS\TEST4.TXT
START /WAIT MSIEXEC /I "%~DP0SETUP.MSI" /QN
SET EXIT_CODE=%ERRORLEVEL%
REM If the instalaltion is successful it should a create installok.log file in 'c:\logs'
IF %EXIT_CODE% EQU 0 ECHO INSTALLED >> %LOGOK%
REM If it fails then it should a create installerr.log file 'c:\logs')
IF NOT EXIST %LOGOK% ECHO FAILED >> %LOGERR%
Output of TEST1.TXT:
log:c:\logs\install.log
logok:c:\logs\installok.log
logerr:c:\logs\installerr.log
Output of TEST1.TXT,TEST2.TXT,TEST3.TXT:
ECHO is on.
Try this:
REM PARAMS ARE [LOG:PATH] [LOGOK:PATH] [LOGERR:PATH]
REM ACCESS WITH '%LOG%', '%LOGOK%' AND '%LOGERR%'
REM SETUP LOCALIZED ENVIRONMENT VARIABLES FOR THE LOG, LOGOK AND LOGERR PARAMS
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%A IN (%*) DO (
ECHO %%A >> c:\Logs\TEST1.TXT
FOR /F "TOKENS=1,2,3 DELIMS=:" %%G IN ("%%A") DO (
SET %%G=%%H:%%I
)
)
ECHO !LOG! >> c:\LOGS\TEST2.TXT
ECHO !LOGOK! >> c:\LOGS\TEST3.TXT
ECHO !LOGERR! >> c:\LOGS\TEST4.TXT
START /WAIT MSIEXEC /I "%~DP0SETUP.MSI" /QN
SET EXIT_CODE=%ERRORLEVEL%
REM If the instalaltion is successful it should a create installok.log file in 'c:\logs'
IF %EXIT_CODE% EQU 0 ECHO INSTALLED >> !LOGOK!
REM If it fails then it should a create installerr.log file 'c:\logs')
IF NOT EXIST !LOGOK! ECHO FAILED >> !LOGERR!
ENDLOCAL
Basically this:
Extends the local scope so that the variables which were assigned inside the FOR loop will be available in the rest of the script
Moves variables to the !delayed! variable syntax in order to cause them to be evaluated as late as possible. See the documentation for "EnableDelayedExpansion" for more details
Note that "ECHO is on." is the output that you get when calling echo with no parameters:
C:\>type echo_test.bat
echo
echo %no_such_variable%
C:\>echo_test.bat
C:\>echo
ECHO is on.
C:\>echo
ECHO is on.

Get a MD5 value from a file using findstr in CMD

I have the following file contents from which I want to extract the MD5 hash value thats on line 2.
How can I do this in a Windows batch file? Unfortunately using powerscript is not an option.
Herewith the input file ( file.txt )
MD5hashoffile20160613190010_Address
f4f855c5cb40767a7227b506f641ceef
CertUtil:-hashfilecommandcompletedsuccessfully.
I wanted to use the findstr utility but the regex I use must be wrong since it's not returning anything.
findstr /R "[a-fA-F0-9]{32}" file.txt
I appreciate any advice.
Thanks
UPDATE :
I have added the full solution in the answer section.
After some trial and error I found a solution that works :
findstr /R "^[a-fA-F0-9]*$" file.txt
Updated Answer with full solution :
SETLOCAL ENABLEDELAYEDEXPANSION
SET "FILESIZE=0"
SET "RECORDCOUNT=0"
SET "MD5HASH="
SET "TEMPHASH="
SET "FILESETREPORT=_UNSET"
SET "LINE=0"
SET "COLUMNS=TableName|RecordCount|FileSize|FileHash"
echo "============================="
echo "= Starting FileSize process ="
echo "============================="
for %%F in (*.csv) do (
echo "Process A CSV File"
for /f "tokens=1,2,3,4 delims=^_" %%A IN ("%%~nF") do (
SET "TABLENAME=%%D"
SET "FILESIZE=%%~zF"
if "!FILESETREPORT!" == "_UNSET" (
SET "FILESETREPORT=%%A_%%B_%%C_FilesetReport.csv"
:: Initialize the headers
echo !COLUMNS! > !FILESETREPORT!
)
)
echo "Get RecordCount in CSV"
if "!TABLENAME!" NEQ "FilesetReport" (
for /f "tokens=*" %%I in ('more +1 %%F ^| find /v /c ""') do SET "RECORDCOUNT=%%I"
echo "Generate File MD5 Hash"
certUtil -hashfile %%~nxF MD5 > hashfile
echo "Get the hash from the file"
for /f "skip=1 tokens=*" %%A in (hashfile) do (
SET "TEMPHASH=%%A"
:: call :cleanHash
if !LINE! == 0 SET "LINE=1" && call :cleanHash
)
:: Reset the Line Number
SET "LINE=0"
echo "Save File Details to FieldsetReport"
echo "RecordCount : !RECORDCOUNT!"
echo "FileSize : !FILESIZE!"
echo "MD5Hash : !MD5HASH!"
echo "TableName : !TABLENAME!"
SET "OUTPUTLINE=!TABLENAME!|!RECORDCOUNT!|!FILESIZE!|!MD5HASH!"
echo !OUTPUTLINE! >> !FILESETREPORT!
:: Cleanup
del hashfile
)
)
echo "File Processing Completed"
exit /b 0
:cleanHash
echo "Remove all spaces from the MD5 hash"
:: for /f "delims=" %%a in ('findstr /R "^[a-fA-F0-9]*$" !TEMPHASH!') do SET TEMPHASH=%%a
SET "MD5HASH=!TEMPHASH: =!"
echo "********************************************************************"
echo !MD5HASH!
ENDLOCAL
You're better off using this:
#echo off
for /f "skip=1" %%a in (file.txt) do set "hash=%%a" &goto breakLoop
:breakLoop
echo %hash%
pause
This should work even if another line also contains only hexadecimal characters, and has the added benefit of putting the md5 hash in a variable, ready to be used.

Read from a file and replace it in another file

I am trying to create a batch file which will read from a file and store the text in a variable. Later this variable has to be replaced in another XML file as explained below
Loop thru the Inputfile by reading line by line i.e. one line after the other
Each time replace the file name that has been obtained from above step in payload.xml
Contine with step 2 until end of file is processed. Example input and output is given below
REM Example Input:        D:\Data\somefile.txt
REM 1st Iteration Output:       D:\Data\file1.txt
REM 2nd Iteration Output:       D:\Data\file2.txt
REM and so on
I am trying to do the following but it is not working. Please kindly help.
SETLOCAL EnableDelayedExpansion
Set AllInputFile=D:\AllInputFile\FileList_for_Import.txt
SET INTEXTFILE=C:\myfolder\payload.xml
ECHO "ERRORLEVEL 0-Sucesss else fail " %ERRORLEVEL% " " %AllInputFile%1>>D:\Data\debuginfo.txt2>>D:\Data\debugerr.txt
ECHO "###########Start of MAIN OF LOOP ############"
for /f "tokens=*" %%a in (%AllInputFile%) do (
ECHO "ERRORLEVEL 0-Sucesss else fail " %ERRORLEVEL% " " line=%%a1>>D:\Data\debuginfo.txt2>>D:\Data\debugerr.txt
set "TARG_FILE=%%a"
ECHO "ERRORLEVEL 0-Sucesss else fail " %ERRORLEVEL% " " "TARG_FILE "%TARG_FILE%1>>D:\Data\debuginfo.txt2>>D:\Data\debugerr.txt
REM Get the string and store it in a variable
for /f "tokens=1*delims=:" %%G in ('findstr /n "^" C:\myfolder\payload.xml') do if %%G equ 2 set "DbgLine=%%H"
ECHO "ERRORLEVEL 0-Sucesss else fail " %ERRORLEVEL% " " "DbgLine "%DbgLine%1>>D:\Data\debuginfo.txt2>>D:\Data\debugerr.txt
SET PREVFILE_NM=%DbgLine:~27,-13%
ECHO %PREVFILE_NM%
call set NewDbgLine=%%DbgLine:!PREVFILE_NM!=!TARG_FILE!%%
echo !DbgLine!
ECHO "ERRORLEVEL 0-Sucesss else fail " %ERRORLEVEL% " " "NewDbgLine "!NewDbgLine!1>>D:\Data\debuginfo.txt2>>D:\Data\debugerr.txt
echo "#######################"
set SEARCHTEXT=%DbgLine%
echo "***************"
echo %SEARCHTEXT%
echo "***************"
set REPLACETEXT=%NewDbgLine%
set OUTPUTLINE=
REM Replace the file name
for /f "tokens=1,* delims=¶" %%A in ( '"findstr /n ^^ %INTEXTFILE%"') do (
SET string=%%A
for /f "delims=: tokens=1,*" %%a in ("!string!") do set "string=%%b"
if "!string!" == "" (
echo.>>%OUTTEXTFILE%
) else (
SET modified=!string:%SEARCHTEXT%=%REPLACETEXT%!
echo %modified%
echo !modified! >> %OUTTEXTFILE%
)
)
ECHO "ERRORLEVEL 0-Sucesss else fail " %ERRORLEVEL% " " "End of Main Loop Iteration#######################"1>>D:\Data\debuginfo.txt2>>D:\Data\debugerr.txt
)
Best Regards,
Ind.
When using enabledelayedexpansion and changing variables in a loop
you need to use !variablename! syntax and not %variablename%

Replace a line with another line using IF - Batch file

I am trying to replace a line in load.xml using the lines read from FileList.txt.
Contents of load.xml
<mainheader>
<InFilePath>D:\Data\All_Inputfiles\oldfile.txt</InFilePath>
</mainheader>
FileList.txt
newfile1.txt
newfile2.txt
Expecting the output with each iteration as
<mainheader>
<InFilePath>D:\Data\All_Inputfiles\newfile1.txt</InFilePath>
</mainheader>
and with the next iteration replace newfile1.txt with newfile2.txt. I am able to get original string with the final string but last part of the code is throwing syntax error, i.e. from
for /f "delims=" %%a in (!INTEXTFILE!) do call :Change "%%a" .
Could please help me?
Thanks in advance.
#echo off
SETLOCAL EnableDelayedExpansion
Set AllInputFile= D:\data\FileList.txt
SET INTEXTFILE=C:\c:\load.xml
set OUTTEXTFILE=D:\data\tmp_out.txt
SET BackupPath=D:\data\backupload.xml
Set TempFile=D:\data\tmp.txt
SET DbgFile=D:\data\debuginfo.txt
Del !TempFile!
Del !DbgFile!
Copy !INTEXTFILE! !BackupPath!
:replace
findstr /g "InFilePath" !INTEXTFILE!>!TempFile!
:: set string=" <InFilePath>D:\Data\All_Inputfiles\oldfile.txt</InFilePath>"
set /p string=< !TempFile!
SET PREVFILE_NM=!string:~75,-13!
set FinalreplaceLine=!string!
set TARG_FILE=%~1
REM ECHO "Before Replace FinalreplaceLine "!FinalreplaceLine!>>!DbgFile!
set FinalreplaceLine=!FinalreplaceLine:%PREVFILE_NM%=%TARG_FILE%!
ECHO "string "!string!>>!DbgFile!
ECHO "FinalreplaceLine "!FinalreplaceLine!>>!DbgFile!
::string has source string and FinalreplaceLine has target string to replace
for /f "delims=" %%a in (!INTEXTFILE!) do call :Change "%%a"
exit /b
:Change
set Text=%~1
if "%Text%"=="%string%" (
(echo !FinalreplaceLine!)>> !OUTTEXTFILE!
) else (
(echo !Text!)>> !OUTTEXTFILE!
)
exit /b
Does this work for you?:
#echo off
for /f "usebackq delims=" %%a in ("FileList.txt") do (
call :change "%%a"
type "load.xml"
pause
)
echo done
pause
goto :EOF
:change
(
echo ^<mainheader^>
echo ^<InFilePath^>D:\Data\All_Inputfiles\%~1^</InFilePath^>
echo ^</mainheader^>
) > "load.xml"

DOS If FINSTR is found set variable to that line and then echo variable?

for /f "tokens=3" %%f in ('find /c /i "apples" "test.txt"') do set varMWG=%%f
REM echo %varMWG%
if %varMWG% EQU 1 (
#echo TRUE
) else (
#echo FALSE
)
instead of echoing TRUE or FALSE I want to echo the variables line if the string is found and still echo FALSE if it is not found.
test.txt contains
fdgsdf
hgsfrtgyr
apples
fdsgfghs
erwyuweu
If all you need is to echo the lines that match or echo FALSE if no lines match (in other words, you don't need the variable), then
findstr /ilc:"apples" "test.txt" || echo FALSE
Remember that there could be multiple lines that match your search.
If you need a variable containing the last found line, then:
set "varMWG="
for /f "delims=" %%S in ('findstr /ilc:"apples" "test.txt"') do set "varMWG=%%S"
if defined varMWG (echo %varMWG%) else echo FALSE
Note - Delayed expansion would be safer. ECHO using regular expansion can fail depending on the content of varMWG.
If you need a variable containing the first found line, then:
set "varMWG="
for /f "delims=" %%S in ('findstr /ilc:"apples" "test.txt"') do (
set "varMWG=%%S"
echo %%S
goto :break
)
:break
if not defined varMWG echo FALSE
This last option would not ever need delayed expansion.
If by "echo the variables line" you mean echo the search string "apples", then the following code should suffice:
#echo off
for /f "tokens=* delims= " %%f in (test.txt) do (
if %%f EQU apples (echo %%f
) else echo false
)
OUTPUT:
false
false
apples
false
false

Resources