2

The user manually types, in a window, the input data, which is stored in variables. Then the batch does an "echo" of the variables that contain the data that the user entered (first.bat):

set source=%HOMEDRIVE%\test\data.txt
mydialogbox=%HOMEDRIVE%\test\myprogram_dialogbox.exe

SetLocal EnableDelayedExpansion

:: dialog box
for /f "tokens=1-3 delims=" %%i in ('%mydialogbox% --forms --title="Dialog" --text="Set Data" --add-entry="USER" --add-entry="PASSWORD" --add-entry="DBNAME" --separator=","') do (
  set line=%%i 
  echo(!line: =!> %source%
)
IF EXIST %source% (GOTO setdata) else (GOTO end)

:setdata
FOR /F "eol=; tokens=1-3 delims=," %%A IN (%source%) DO (
    set dbuser=%%A
    set dbpass=%%B
    set dbname=%%C
)
echo your imput: %dbuser% %dbpass% %dbname%

out e.g.:

your input: mydb zuckerberg dadada

So I need to replace this values (of these variables: %dbuser% %dbpass% %dbname%) in another script (second.bat)

set dbname=foo
set dbuser=bar
set dbpass=blabla

expected output (Change cannot be dynamic, but permanent):

set dbname=mydb
set dbuser=zuckerberg
set dbpass=dadada

how I do this?

PS: On linux this is easy

sed -e "s:$dbuser:zuckerberg:g" second.bat

PS: If what I'm asking doesn't work, then is there a way to use the output of the %dbuser% %dbpass% %dbname% variables from first.bat into second.bat

thanks

Update:

  1. I am using fart-it and it has worked:

first.bat:

fart.exe second.bat "zuckerberg" "%dbuser%"
fart.exe second.bat "dadada" "%dbpass%"
fart.exe second.bat "mydb" "%dbname%"

But I have to execute 3 times the same command for each replacement. And I would like to know if there is another solution (.bat, .cmd) that does not depend on external programs

  1. Another solution is to put the output of the "echo" in variables in second.bat:

first.bat:

echo your imput: %dbuser% %dbpass% %dbname%

second.bat:

FOR /F "tokens=*" %%g IN ('echo %dbuser%') do (SET myuser=%%g)
etc

but this does not permanently replace the values of variables of the second script (which is what I want).

  1. Another solution is this (first.bat):
(for /f "tokens=1* delims=:" %%a in (%source%) do (
 if "%%b"=="" (echo %%a) else (
  echo %%a|find " id" >null&& echo %%a: ||echo %%a: %%b
 )
))>second.bat

But I have not been able to adjust it to my interests, since it rewrites the output (does not search and replace the strings)

  1. Another solution is with replacer.bat:
call replacer.bat "second.bat" "zuckerberg" "%dbuser%"

It has the same problems as fart-it. I have to run a command for each replacement (this is not very optimized for my code) and would depend on an external script.

6
  • are you hard set on using cmd and not powershell? Is combining the 2 scripts into one a possibility? As-is, you can append all the data to a text file and then read it in on the second bat and delete the file after it processes the variables.
    – Narzard
    Commented Oct 27, 2022 at 19:50
  • Unfortunately I can't merge the scripts (I wish I could) and I can't use powershell either (it doesn't go with my environment). I am trying with fart-it program and it has worked very well for this purpose (sourceforge.net/projects/fart-it), but I would like to know if there is another solution (in batch, cmd) that does not depend on external programs.
    – acgbox
    Commented Oct 28, 2022 at 13:21
  • You're right, but it should be a definite replacement, with data, not other variables
    – acgbox
    Commented Oct 28, 2022 at 15:09
  • 1
    @VomitIT-ChunkyMessStyle. There was no need for you to remove your post as your answer is pretty close to what I'm looking for
    – acgbox
    Commented Oct 28, 2022 at 20:37
  • Okay, I undeleted it since you said it was close and should not have been deleted—I thought I was way off. I deleted some of my other comments, but if interested in 100% pure batch executed script with PowerShell helper logic that gets executed within a batch script, let me know and I can append another variation to my answer with that. Maybe your systems restrict powershell.exe though or you aren't aware powershell.exe can be used in a batch script just like sed or fart can but it more robust and Windows native with no 3rd party needed. Just let me know and I'll be happy to try to help more. Commented Oct 28, 2022 at 21:05

4 Answers 4

1

Passing in classic batch script cmd arguments when executing the second.bat should do this no problem. Using this method eliminates the need altogether to even have to change any content of second.bat.

It essentially makes second.bat dynamic and uses the passed in argument paramater(s) as variables which contain the placeholder values (e.g. %~1,%~2, etc.) for the passed in argument values (e.g "flockingbird" "clockingmerge" "wishyword").

Second.bat

SET "dbuser=%~1"
FOR /F "tokens=*" %%g IN ('echo %dbuser%') do (SET "myuser=%%~g")
etc

Executing

You can choose whatever method works best for executing or calling the second.bat script whether using call, start, something like second.bat "flockingbird" or any other ways that works to pass in the argument value at execution time of second.bat


Another Example

Batch

@echo off
set "dbname=%~1"
set "dbuser=%~2"
set "dbpass=%~3"

echo %dbname%
echo %dbuser%
echo %dbpass%

pause

To Execute

C:\Folder\second.bat "flockingbird" "clockingmerge" "wishyword"

Output

flockingbird
clockingmerge
wishyword

Supporting Resources

  • Command line parameters

    Batch files can only handle parameters %0 to %9

    %0 is the program name as it was called, %1 is the first command line parameter, %2 is the second command line parameter, and so on till %9.

  • Pass Command Line arguments (Parameters) to a Windows batch file

    %~1 Expand %1 removing any surrounding quotes (")

  • Start

  • Call

    CALL a second batch file

    The CALL command will launch a new batch file context along with any specified parameters. When the end of the second batch file is reached (or if EXIT is used), control will return to just after the initial CALL statement.

    Arguments can be passed either as a simple string or using a variable:

    CALL MyScript.cmd "1234" CALL OtherScript.cmd %_MyVariable%

7
  • I have updated the question adding more details of first.bat. thanks
    – acgbox
    Commented Oct 28, 2022 at 13:09
  • Change cannot be dynamic in second.bat, but permanent
    – acgbox
    Commented Oct 28, 2022 at 13:11
  • Changing it to dynamic one time, is "permanent" then no need to edit "content" of second.bat but that one time only to specify the name of the variable up top set to the argument value that's passed it, then that variable in hundred or thousands of lines below will be just that value everywhere for the exact result you need. This is a classic example here actually. You'd just add before (or after) the echo input line second.bat "%dbuser%" "%dbpass%" "%dbname%" . @acgbox Commented Oct 28, 2022 at 14:51
  • Then you'd only add three new lines in second.bat just one time and no need to change or add anything else ever. Just add the three lines set "dbname=%~1", set "dbuser=%~2", and set "dbpass=%~3" to second.bat. Now run it and everything should work/connect to SQL as expected from form specified input setting variable output to be another script variable input. Is the issues the user specifying input does not have execute access themselves to execute second.bat or are they not able to make the SQL connections themselves and another process executes that. Task Scheduler will help here Commented Oct 28, 2022 at 14:52
  • 1
    I will adapt my script to this new reality. Thank you
    – acgbox
    Commented Oct 28, 2022 at 21:57
1

You can use the call function to pass the variables.

%source% in your code, I will reference as file.txt here.

file.txt contents:

really,big,rabbit

test1.bat contents:

FOR /F "eol=; tokens=1-3 delims=," %%A IN (file.txt) DO (
    set dbuser=%%A
    set dbpass=%%B
    set dbname=%%C
)
call test2.bat

test2.bat contents:

@echo OFF
echo db user is %dbuser% 
echo db pass is %dbpass%  
echo the dbname is %dbname%

Now if you run test1.bat in cmd, you get as the output:

db user is really
db pass is big
the dbname is rabbit

test2.bat is where you can put the variables that need to run as your second batch to do something with those parameters.

2
  • ok for %source%, but your sequence is incomplete or not what I'm looking for, since it doesn't replace the values of variables, which is what I need (see "expected output")
    – acgbox
    Commented Oct 27, 2022 at 22:49
  • I have updated the question adding more details of first.bat. thanks
    – acgbox
    Commented Oct 28, 2022 at 13:09
0

You can't share local variables among CMD sessions.

You need to use a global mechanism for making them accessible from another session, for example a common file, the registry or system variables (see the command setx).

1
  • and is there another way to do this?
    – acgbox
    Commented Oct 27, 2022 at 19:36
-1

Here's an example of the the logic involved in handling a first run initialization. Additional validation of data passed as arguments by user input strongly recommended.

@Echo off

Set "var1="
Set "var2="
Set "var3="

Rem if file called with 3 arguments
If not "%~3" == "" (
    If not exist "%TEMP%\%~n0_firstrun.dat" (
        <nul set /p "=Initiallizing... "
        Rem assumes delayed expansion state is disabled
        Set "var1=%~1"
        Set "var2=%~2"
        Set "var3=%~3"
        >"%TEMP%\%~n0_firstrun.dat" (
            Setlocal EnableDelayedExpansion
                Echo Set "var1=!var1!"
                Echo Set "var2=!var2!"
                Echo Set "var3=!var3!"
            Endlocal
            Rem optional - use conditional operator to flag write permission / filename error to calling script
        ) || (
            Echo Failed - Permission or Filename error
            exit /b 1
        )
        Rem Optional - guard initialization file from accidental user deletion
        REM Attrib +R "%TEMP%\%~n0_firstrun.dat"
        echo - Initiallization Complete
    )
) Else If not exist "%TEMP%\%~n0_firstrun.dat" If not "%~1" == "" If "%~3" == "" (
    Echo Initiallization Failed - Insufficient arguments provided
    Exit /B 2
)
cls
Rem attempt to load the variables.
Rem flags error in the event user has deleted the initialization file 
(For /f "UsebackQ delims=" %%G in ("%TEMP%\%~n0_firstrun.dat")Do %%G) || (
    Rem user has deleted the initialization file
    Exit /b 2
)

Set Var
Pause
5
  • Did you read the remarks in the script that explain the actions? If so, what are you not understanding. The script is an example showing how to handle the logic involved in saving initialization values to a file for retrieval in subsequent executions. The save only happens if the required conditions are true, which are: they have not been saved previously, and the script has been provided enough arguments to store the expected number of variables.
    – T3RR0R
    Commented Nov 1, 2022 at 6:47
  • Thats all you get, if you cant take the time to integegrate it or ask specific questions, so be it. Every step is already explained in the remarks. If your still uncertain about a specific section or element, ask. Im not going to guess at what you do and dont understand or make assumptions about how much or little you know.
    – T3RR0R
    Commented Nov 1, 2022 at 19:23
  • Sounds very much like "write a script to solve my specific problem so I can just use it". If there's something specific your not understanding in the remarked example script, it's an easy thing to ask. What this script demonstrates is a solution to storing passed variables when first run so they are avialable for future use. The logic to store the variables only activates if the storage file does not exist, and only loads them if they have already been stored. A number of error checks are demonstrated that are advisable to use given you have stated 1st.bat will be deleted after the first run.
    – T3RR0R
    Commented Nov 6, 2022 at 11:04
  • The script contains explanations. If theres something your not understanding, it's for you to ask about said something. Do you need to have the basics of an If / Else statement explained? Do you know what && or || conditional oiperators do, or that %1 etc are arguments? Do use know that ">" writes to a file, and "<" reads from it? There is no way for me to know what you do and don't understand in the script, What if any level of understanding you have of batch scripting, hence why I very reasonably ask you to be specific - so I don't waste my time over-explaining basic batch ...
    – T3RR0R
    Commented Nov 7, 2022 at 17:25
  • commands that can be learned about by reading help output or doing even the slightest bit of research
    – T3RR0R
    Commented Nov 7, 2022 at 17:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .