batch script how to check if variable exist then replace variable with another - variables

I've tried looking every where how to do this but I cant find out how.
How do I check if a variable is defined and if it is replace every in variable in that file with a different variable. thanks
okay here is the code
#echo off
set/p "directoryname= Name of directory (to run on startup type "startup"). : "
if %directoryname%==startup goto startup
:namedirectory
if not exist "%directoryname%" (
mkdir "%directoryname%"
if "!errorlevel!" EQU "0" (
echo Folder created successfully
) else (
echo Error while creating folder
)
) else (
echo Folder already exists
)
goto skip_startup
:startup
:: here i would like to check if the variable %directoryname% is defined,
:: and it is, replace the variable named %directoryname% with
:: (Not changing the variables name) with the directory,
:: "C:\Documents and Settings\All Users\Start Menu\Programs\Startup". that
:: way when ever i can recall my variables in my file i can change my folder
:: to the startup directory.
:skip_startup
cd %directoryname%
:: ^
:: |_ replaced variable

Here is the commented batch code with the requested and some more enhancements:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Define as default directory name "startup". The user has to hit just
rem ENTER or RETURN with this default value and variable DirectoryName
rem keeps the default value "startup". Then ask user for directory name
rem and remove all double quotes from the entered directory name.
:EnterDirectory
set "DirectoryName=startup"
echo Please enter the name of the directory.
echo/
echo Hit just RETURN or ENTER to run on startup directory.
echo/
set /P "DirectoryName=Name of directory: "
set "DirectoryName=%DirectoryName:"=%"
rem Check if something other than just one or more double quotes was entered.
rem Prompt user once more after clearing screen if this is really the case.
if not defined DirectoryName cls & goto EnterDirectory
if "%DirectoryName%" == "startup" goto Startup
rem Check if entered directory name does not contain only spaces.
if "%DirectoryName: =%" == "" cls & goto EnterDirectory
echo/
if not exist "%DirectoryName%" (
mkdir "%DirectoryName%"
if errorlevel 1 (
echo Error on creating folder: "%DirectoryName%"
) else (
echo Folder "%DirectoryName%" created successfully.
)
) else (
echo Folder "%DirectoryName%" already exists.
)
goto SetDirectory
rem The variable DirectoryName has the default value "startup". Replace
rem this value by directory path of "Startup" folder in all users start
rem menu of Windows.
:Startup
set "DirectoryName=%ALLUSERSPROFILE%\Start Menu\Programs\Startup"
rem Set current directory to "Startup" directory or entered directory.
:SetDirectory
endlocal & cd /D "%DirectoryName%"
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.
cd /?
cls /?
echo /?
endlocal /?
goto /?
if /?
mkdir /?
rem /?
set /?
setlocal /?
See also:
Single line with multiple commands using Windows batch file
DosTips forum topic: ECHO. FAILS to give text or blank line - Instead use ECHO/

Related

batch file to start Catalina.bat file

I want to create batch file to start/stop catalina.bat file on window server.
#echo off
cls
cd D:\apache-tomcat-7.0.75-windows-x86\apache-tomcat-7.0.75\bin
catalina.bat start
this is what I create but not working.
If you type CD /? at the command prompt you'll note it has a /D option for changing drives.
You could therefore try:
#Echo Off
ClS
CD /D "D:\apache-tomcat-7.0.75-windows-x86\apache-tomcat-7.0.75\bin"
catalina.bat start <args>
If you don't need to have your working directory as the \bin location you could just use:
#Echo Off
ClS
"D:\apache-tomcat-7.0.75-windows-x86\apache-tomcat-7.0.75\bin\catalina.bat" start <args>
To stop it, repeat the last line, ending it with stop instead of start
Edit
If you really do need to use it, and given that you said the Call command works, you could useā€¦
Either:
#Echo Off
ClS
Rem start it
Call "D:\apache-tomcat-7.0.75-windows-x86\apache-tomcat-7.0.75\bin\catalina.bat" start <args>
Rem Do some other stuff
Timeout 120 >Nul
Rem stop it
Call "D:\apache-tomcat-7.0.75-windows-x86\apache-tomcat-7.0.75\bin\catalina.bat" stop
Or:
#Echo Off
ClS
Rem Make \bin directory current
CD /D "D:\apache-tomcat-7.0.75-windows-x86\apache-tomcat-7.0.75\bin"
Rem start it
Call catalina.bat start <args>
Rem Do some other stuff
Timeout 120 >Nul
Rem stop it
Call catalina.bat stop
If you want to create a .bat file to start your Tomcat, then here it goes:
Declare the JAVA_HOME & CATALINA _HOME path in the system environment variables.
Create a file in Notepad with the .bat extension and put the following code within the respective Tomcat directory:
set JPDA_ADDRESS=8000
set JPDA_TRANSPORT=dt_socket
C:
cd C:\Program Files\Apache Software Foundation\Tomcat 9.0 //Enter Your Tomacat Path
call .\bin\catalina jpda start
Check out the image attached for more detailed explanation.

Batch scripting for executing SQL scripts in a directory

I want to develop a batch script which will execute each .sql SQL scripts present in the folder where the batch file is placed to and record the logs to a filename_sqloutput.txt file .
The condition is : If any script gives any error message like column name incorrect , or table name etc. The script execution should stop immediately and further scripts should not executed .
I tried with the below code: But its not working as even if the script is giving errors in the output file . The script execution is not stopping ..
Need your help !!!
#echo off
for /f %%a IN ('dir /b *.sql') do (call sqlcmd -S AMRVSP000000318 -i %%a -o"%%~na_sqloutput.txt"
findstr "Msg" %%~na_sqloutput.txt >nul & if %errorlevel% EQU 1 (exit) else (echo Successfully executed %%~na_sqloutput.txt)
)
pause
FINDSTR will set %ERRORLEVEL% as follows:
0 (False) a match is found in at least one line of at least one file.
1 (True) if a match is not found in any line of any file, (or if the file is not found at all).
2 Wrong syntax
An invalid switch will only print an error message in error stream.
Moreover, follow EnableDelayedExpansion article and rewrite the script to more readable structure:
#echo off
SETLOCAL EnableExtensions EnableDelayedExpansion
for /f %%a IN ('dir /b *.sql') do (
call sqlcmd -S AMRVSP000000318 -i %%a -o"%%~na_sqloutput.txt"
findstr "Msg" "%%~na_sqloutput.txt" 2>NUL
if !errorlevel! EQU 0 (
echo error occured %%~na_sqloutput.txt
rem pause to see error
pause
exit /B
) else (
echo Successfully executed %%~na_sqloutput.txt
)
)
pause
.... if errorlevel 1 (exit...
%errorlevel% is the initial value of errorlevel as it stands when the for is encountered.
See endless SO articles about using delayed expansion as another solution.
This syntax means "if the current errorlevel is 1 or greater dothis else dothat"

"Echo is OFF" text always inserted into batch file when SET variable is written to a batch file IF the file is made by another batch program

I am trying to create a batch file using another batch program using:
#echo {code here}>>batch-program.bat, but whenever I try to write code to write the contents of a SET variable to a text file, the batch program does not write the code into the other batch file, but instead writes "Echo is OFF."
Code is here:
#echo off
#echo #echo off>>apt.bat
#echo color 2A>>apt.bat
#echo echo example-batch>>apt.bat
#echo cd C:/Users/Default/apt/assets>>apt.bat
#echo mkdir cmdInput>>apt.bat
#echo cd C:/Users/Default/apt/assets/cmdInput>>apt.bat
#echo set /p cmdInput= cmd->>apt.bat
#echo %cmdInput%>>used-cmdInput.txt>>apt.bat
#echo pause>>apt.bat
This should have created a batch file named apt.bat, and written into the batch file:
#echo off
echo color 2A
echo example-batch
cd C:/Users/Default/apt/assets
mkdir cmdInput
cd C:/Users/Default/apt/assets/cmdInput
set /p cmdInput= cmd-
%cmdInput%>>used-cmdInput.txt
pause
but the 9th line (%cmdInput%>>used-cmdInput.txt)
is instead converted into the text line "Echo is OFF".
Have I done anything wrong, or is it just a really weird bug?
EDIT: I found another problem in the program, that because mkdir cmdInput is always run when apt.bat is run, so it displays a error message because of apt.bat trying to create the directory cmdInput though it already exists. apt/assets. So I have changed the code a bit, so that the directory cmdInput is created in the first "creation" batch file (the program that was used to create apt.bat). mkdir cmdInput has been removed from apt.bat.
You need to escape > with ^ but you need to escape % with %
#echo %%cmdInput%%^>^>used-cmdInput.txt>>apt.bat
unless you want to output the contents of cmdinput where you need
#echo %cmdInput%^>^>used-cmdInput.txt>>apt.bat
You can add 2>nul to the end of a md command to suppress the error message generated if the directory already exists.
You should use backslashes \ in directorynames, not forward slashes /. In winbat, the forward slash is often used for command switches. Sometimes forward slashes will work for directorynames, but backslashes always work.
You just have to "escape" the percent-signs with another % and other special chars like > with a caret) to prevent evaluation of your variable %cmdInput% (which probably is empty - therefore the Echo is off).
Also a single #echo off is sufficient. No need to add a # to every line.
#echo off
echo #echo off>>apt.bat
echo color 2A>>apt.bat
echo echo example-batch>>apt.bat
echo cd C:/Users/Default/apt/assets>>apt.bat
echo mkdir cmdInput>>apt.bat
echo cd C:/Users/Default/apt/assets/cmdInput>>apt.bat
echo set /p cmdInput= cmd->>apt.bat
echo %%cmdInput%%^>^>used-cmdInput.txt>>apt.bat
echo pause>>apt.bat
A more elegant way is to use only a single redirection (cmdhas to open the file for writing just once):
#echo off
(
echo #echo off
echo color 2A
echo echo example-batch
echo cd C:/Users/Default/apt/assets
echo mkdir cmdInput
echo cd C:/Users/Default/apt/assets/cmdInput
echo set /p cmdInput= cmd-
echo %%cmdInput%%^>^>used-cmdInput.txt
echo pause
)>apt.bat

Batch file which saves user input path with spaces to a text file. (win 7)

First of all i am a noob in programming.
I am trying to make a batch file which takes an installed directory of a program as user input when run for the first time (means it should not ask for the directory the second time it is run). By searching for various scripts, i reached till here,
#echo off
Echo =============================================
echo Directory
Echo =============================================
setlocal enableextensions enabledelayedexpansion
set /p mypath=Please specify install directory;
Echo %mypath% ----was what you typed
pause
echo start>temp.txt
echo %mypath%>>temp.txt
echo \programfolder\program.exe>>temp.txt
echo -argument -argument>>temp.txt
setlocal enabledelayedexpansion
set FINAL=
for /f %%a in (temp.txt) do (
set FINAL=!FINAL!%%a
)
echo %FINAL%>input.txt
del /q temp.txt
Pause
start "<input.txt"
This saves the input path in the "input.txt" text file, and runs the program the next time it is launched.
I want the text file to have the saved path as "start driveletter:\foldername\foldername with spaces\programfolder\program.exe" -arguments
However the "start", "program folder", "program.exe" and "-arguments" are fixed.
The user input path should get saved in- %mypath%.
The does what you asked, I think:
#echo off
if exist "go.bat" go.bat
set /p "mypath=Please specify install directory; "
Echo "%mypath%" ----was what you typed
pause
>"go.bat" echo #start "" "%mypath%\programfolder\program.exe" -argument -argument

Batch Help -- Move File To Directory, If Exist Filename, Rename 001

I have a batch file that checks a root directory every 10 seconds for PDF files and copies those files to their corresponding subfolders of the exact same name.
What I'm missing is that I need my batch file to check the target subdirectory for the named file, and if the named file exists, to rename the new file to be copied to !filename!001.pdf and have the 001 get incremented as duplicate file names are copied. Here's what I got:
:loop
setlocal enabledelayedexpansion
cls
pushd c:\files\
for /f "tokens=*" %%1 in ('dir /a-d /b c:\files\*.pdf') do (
set filename=%%~n1&set dirname=!filename:~0,7!
dir c:\files /b *.pdf > location1list.tmp
for /f %%a in (location1list.tmp) do dir c:\files\%%a > location2list.tmp
if not exist c:\files\!dirname! (md c:\files\!dirname!)
move %%1 c:\files\!dirname!\>nul
)
timeout /t 10
goto:loop
Any suggestions how I can get the files renamed?
I.e. if Bob.pdf exists in the Bob folder and another Bob.pdf is added to the C:\files folder, I want it to be copied to the C:\files\bob folder as Bob001.pdf.
Something like this should do what you want. May need some tweaking. Also I have not tested it, just wrote it from memory. Need any explanations, just ask.
Script
#echo off
setlocal EnableExtensions EnableDelayedExpansion
pushd C:\files
:Main
for /f "tokens=*" %%A in ('dir /a-d /b *.pdf') do (
if not exist "%%~dpnA\*" md "%%~nA"
set "File=%%~dpnA\%%~nxA"
if exist "!File!" call :Name "!File!" File
echo !File!
move "%%~fA" "!File!"
)
goto Wait
:Name <Target> <Variable>
set "Count=0"
:Count
set /a "Count+=1"
set "Number=00%Count%"
if exist "%~dpn1%Number:~-3%%~x1" goto Count
set "%~2=%~dpn1%Number:~-3%%~x1"
goto :eof
:Wait
timeout /t 10
goto Main
:End
popd
endlocal
Limitations
Each target subdirectory can only handle a maximum of 1000 files as this is written. If the subdirectory hits this maximum then the script will get stuck in an infinite loop.
Update
Fixed an error in my initial script