CMD appears not to recognize variables - cmd

CMD does not appear to be recognizing any variable I store using SET. If I run this batch file:
#ECHO off
SET /P name = What is your name?
ECHO %name%
PAUSE
ECHO on
I get the following output:
What is your name? steven
ECHO is off.
Press any key to continue . . .
When I run line 2 and then line 3 from the command prompt, it just prints:
%name%
Do I have something configured incorrectly? Am I correct in thinking that line 2 should create a session variable that should be recognized in line 3?
I searched, but I could only find answers related to variable expansion within IF blocks. This is happening to me outside any IF/FOR/etc blocks.
This is Windows 7, by the way. I'm not sure how much cmd changes from one version of Windows to another.

There must not be any spaces around the equal sign in the set instruction. Change this
SET /P name = What is your name?
into this
SET /P name=What is your name?
and your problem will disappear.

since I can not add any comments yet I have to post a new answer. The information:
"There must not be any spaces around the equal sign in the set instruction."
is only partly correct. To be exact it should say: the equal sign must follow directly after the variable name (in sricks3's case without a space). Whatever comes after the equal sign will be used as input-prompt for the variable including any spaces, so the following code will work as well:
SET /P name= What is your name?

Related

How to output multiple user input values into a single variable in BATCH using Windows 7?

SOLVED!
Update: It figures moments after posting for help which is something I never do I'd figure it out...I tend to over think things, and that was the case here, it was just so simple! >.<
Solution:
(This worked under Windows 7 Ultimate 64 Bit)
Set var=
Set var=SomeText %var1% %var2% %var3%
Echo %var% > output.txt
See an explanation in my answer below.
I've been searching and trying several posts here similar to my question for hours with no success. I'm not new to Programming in BATCH but I have memory problems and thus can't always remember things. It also doesn't help that I program in other languages on other platforms which usually means I'm trying to use *nix shell commands in my Windows Batch scripts >.<
I've gotten quite close with some examples but nothing that works as needed.
Ideally, I'd like this work to work on Windows 7, 8, 8.1, Vista and 10 as that is the intended target.
This is what I need to accomplish:
The user will answer a series of questions, each question is stored into a .txt file (or variable if you prefer. I just used text files because of a past project where I ran into issues with variables that couldn't be solved and text files worked). The lines in each text file will need to be output into a single text file, on a single line which will then be read back in as a variable and run. Again, you could just use and combine the variables in your example if that's easier for you or both of us ;P
This is a snippet example of how I was doing it
SET file1=
SET /P file1=file1:%=%
ECHO %file1% > file1.txt
Then
copy /b file1.txt + file2.txt + file3.txt + file4.txt output.txt
Here is how I'd like the result to look
toolkit /S "C:\ToolKit Bravo\Data\etc" "D:\ToolKit Bravo\Data\Ops"
The "" quotation marks are necessary. The output MUST be EXACTLY as shown above for the example I've given. The "/S" & paths are variable NOT fixed!
Here is the best I've been able to come up with using variables..
"toolkit /S "C:\ToolKit Bravo\Data\etc" "D:\ToolKit Bravo\Data\Ops""
Update 2 - An explanation as requested:
The paths in the above example directly above this are not fixed! This was an Example Only. "toolkit" is fixed, this doesn't change. "/S" is an option selected by the user to pass on to the "toolkit". Both the source and destination paths are again input by the user in "quotation" marks. They're not fixed paths.
As you can see the result is surrounded by quotations which is NOT acceptable. And Please remember, I NEED the quotations around the paths in the end result, so removing them all is NOT an option!
Any help is greatly appreciated! Thank you for your time.
Just take all of the characters between the quotes.
SET X="toolkit /S "C:\ToolKit Bravo\Data\etc" "D:\ToolKit Bravo\Data\Ops""
ECHO %X%
SET Y=%x:~1,-1%
ECHO %Y%
Solution:
This solved my problem under Windows 7 Ultimate 64 Bit
Set var=
Set var=SomeText %var1% %var2% %var3%
Echo %var% > textfile.txt
Using the SET command I first made sure the variable or var for short was empty. Using this command:
Set var=
I then proceeded to create my variable using all of the other variables I had created and wanted to combine using this line of code:
Set var=SomeText %var1% %var2% %var3%
Note that I have preceded the variables with "SomeText". This is where I'll place the name of the .exe I'm passing the arguments to, but it can be anything you want included. I also need spaces between each variable so I've left spaces between them in the example code. If you don't want the spaces simply remove them, and you'll have 1234, instead of 1 2 3 4.
Finally I send the combined variable out to a .txt file.
Echo %var% > textfile.txt
However, you could also simply call the new variable now like this:
%var%

Word Sorting in Batch

Right let me rewrite this try to make it more clear.
Picture added to make this even clearer:
I have two files
File 1, contains words.
file 2, contains commands.
I need to put words from FILE 1
into FILE 2
I cannot copy-paste them one by one, because there is a LOT of words in FILE 1
File 1 is listed in alphabetical order (by first letter)
File 2 the command does not change
The issue is getting words from file 1 into file 2
but they have to be moved into quotes " " in file 2
so a script that could for example..
Take apple from file 1 and move it between quotes admin.executemotecommand "apple"inside file 2 as it goes down the list keeping the words in order as they move them across.
This could perhaps be done the same way around in which, the script writes the command in front of the words in file 1 as it goes down file 1's list
Is this even possible? I've never seen this done anywhere else and completely clueless if batch is even the right language for it.
The question is a little confusing, but based on your responses in the comments my understanding is that you don't necessarily need the script to edit a preexisting file 2, because you're repeating the same command(s) for each word, so the script can just create a new file based on the words in file 1.
You can do it at the prompt like this:
FOR /F %a IN (words.txt) DO ECHO admin.executeremotecommand "%a" >> commands.txt
The original version of the question indicated that you want more than one command for each word. I take it you changed that in order to simplify that question, and figured you'd just run the script once for each command? However, it's quite simple to have it produce more than one command for each word:
FOR /F %a IN (words.txt) DO (ECHO first.command "%a" & ECHO second.command "%a") >> commands.txt
In a batch file, you'd do it this way:
#ECHO OFF
FOR /F %%a IN (words.txt) DO (
ECHO first.command "%%a"
ECHO second.command "%%a"
) >> commands.txt
BTW, in the code in some of your comments, you surrounded the variable with %'s (%A%). That's incorrect; it would evaluate to the value of %A followed by a literal %. Surrounding with %'s is used only for environment variables. (Note that the %'s around environment variables do not get doubled in a batch file. For example, to get the current date, use ECHO %date% both at the prompt and in a batch file.)

Renaming file with Batch variable

I have the following code:
set DATE=%date%
echo %DATE%
set DAY=%DATE:~0,2%
echo %DAY%
rename file09.txt file%DAY%09.txt
pause
It is supposed to rename a text file and put the day of the month in the file name. I am however getting a syntax error on the rename command.
I think the problem is in inserting the variable into the file name. Any help would be appreciated. The echos are just in the program for my own reference.
As has already been stated - your code as pasted had trailing spaces on many lines and the spaces often matter. I posted this because you had reused the system DATE variable name and that causes issues, and to show you that quotes are often helpful - and needed with long filenames.
set "D=%date%"
echo "%D%"
set "DAY=%D:~0,2%"
echo "%DAY%"
rename "file09.txt" "file%DAY%09.txt"
pause
you might have trailing spaces in the set command. Just try this:
set "DAY=%DATE:~0,2%"
btw. with set DATE=%date% you doesn't create a new variable. Variables must have case insensitive unique Names.
The problem was the date configuration, because of that the content of the variables is wrong.
Really use quotation marks worked as it ensures full name if the variables have spaces or unusual characters.
Review my post for view the Endoro answer..it works right for me
Renaming file with Batch variable doesnt work with another user profile
"Renaming file with Batch variable doesnt work with another user profile"

Echo misses ^ characters when long string

I have the following command in a windows batch script
echo =%%k-16,INDIRECT.EXT^("'C:\Users\...\Analysis\[ObsStreamflow.xlsx]Sheet1'^!A%%k"^),INDIRECT.EXT^("'C:\Users\...\Analysis\[sim%%j.xlsx]Sheet1'^!B!val!"^),^=C%%k/1000,^=D%%k-B%%k,^=ABS^(E%%k^),^=(E%%k^)^^2,=^(B%%k-B10^),=Sqrt^(B%%k^),=SQRT^(D%%k^),=^(J%%k - B13^)^^2 >>t%%j.csv
where the omitted file path is 38 characters long (I don't think I'm hitting the line limits, but just in case this is the problem). This is a single line in my .bat file, shown here as multiple lines just to make things more readable.
The output is mostly correct, except that where I have ^^2, it just becomes 2 (so I have =(E1)2 and =(J1-B13)2. If I omit the Indirect.Ext text, and just have
echo =%%k-16,a1,b1,^=C%%k/1000,^=D%%k-B%%k,^=ABS^(E%%k^),^=(E%%k^)^^2,=^(B%%k-B10^),=Sqrt^(B%%k^),=SQRT^(D%%k^),=^(J%%k - B13^)^^2 >>t%%j.csv
it prints correctly, so the relevant comments show as =(E1)^2 and =(J1-B13)^2, which is what I am after.
I've not had any luck finding an answer, everything I have found just points to using ^^ to get echo to return ^. I cannot break this command into multiple lines, I need it to be a single row in csv format.
Any suggestions for a fix much appreciated, I only really need to use this for a week or so, don't need an elegant solution, just one that works. - I'm very new to bat scripts (and indeed programming in general), will keep trying different ideas in the mean time.
It's only the exclamation mark that creates the problems for you.
If at least one ! is in your line (and delayed expansion is enabled), then a second caret escape phase will be started.
In this phase quotes aren't regarded, only carets.
A small test
setlocal EnableDelayedExpansion
echo one^1
echo two^^2
echo two^^2 With exclam!
echo five^^^^^& With exclam!
Output
one1
two^2
two2 With exclam
four^& With exclam
So in your sample, you need five carets.
Four to create one caret and the last one to escape the ), as the escape of the special character is only once required.
Not sure what your specific problem is but you can use a trick in Windows to emulate echo -n (echo without a newline).
The commands:
<nul: >file.csv set /p junk=first field
<nul: >>file.csv set /p junk=,second field
>>file.csv echo ,third field
will result in a single line:
first field,second field,third field
That may make it easier for you to avoid the specific problem and, as a bonus, clean up your script so it's a little more readable (such as one field per script line).
It works because set /p var=prompt is the input command. It first outputs prompt without a newline then waits for the user to enter something, assigning it to the var environment variable.
By getting input from nul:, you basically give it an empty string so it doesn't wait. The prompt is output to file.csv without the newline.
In any case, for something this complex, I'd be bypassing cmd.exe for something a little more powerful such as the UNIX text processing tools under CygWin or MinGW (which require installation but are well worth it), or even VBScript scripts (which should be on Windows by default), where you can more easily control the output.

Check for null variable in Windows batch

I'm working on a Windows batch file that will bcp three text files into SQL Server. If something goes wrong in production, I want to be able to override the file names. So I'm thinking of doing something like this.
bcp.exe MyDB..MyTable1 in %1 -SMyServer -T -c -m0
bcp.exe MyDB..MyTable2 in %2 -SMyServer -T -c -m0
bcp.exe MyDB..MyTable3 in %3 -SMyServer -T -c -m0
I would like to be able to enter default names for all three files, to be used if the positional parameters are not supplied. The idea would be either to execute
myjob.bat
with no parameters, and have it use the defaults, or execute
myjob.bat "c:\myfile1" "c:\myfile2" "c:\myfile3"
and have it use those files. I haven't been able to figure out how to tell if %1, %2 and %3 exist and/or are null. I also don't know how to set those values conditionally. Is this possible? Any suggestions would be appreciated.
To test for the existence of a command line paramater, use empty brackets:
IF [%1]==[] echo Value Missing
or
IF [%1] EQU [] echo Value Missing
The SS64 page on IF will help you here. Under "Does %1 exist?".
You can't set a positional parameter, so what you should do is do something like
SET MYVAR=%1
You can then re-set MYVAR based on its contents.
The right thing would be to use a "if defined" statement, which is used to test for the existence of a variable. For example:
IF DEFINED somevariable echo Value exists
In this particular case, the negative form should be used:
IF NOT DEFINED somevariable echo Value missing
PS: the variable name should be used without "%" caracters.
Both answers given are correct, but I do mine a little different. You might want to consider a couple things...
Start the batch with:
SetLocal
and end it with
EndLocal
This will keep all your 'SETs" to be only valid during the current session, and will not leave vars left around named like "FileName1" or any other variables you set during the run, that could interfere with the next run of the batch file. So, you can do something like:
IF "%1"=="" SET FileName1=c:\file1.txt
The other trick is if you only provide 1, or 2 parameters, use the SHIFT command to move them, so the one you are looking for is ALWAYS at %1...
For example, process the first parameter, shift them, and then do it again. This way, you are not hard-coding %1, %2, %3, etc...
The Windows batch processor is much more powerful than people give it credit for.. I've done some crazy stuff with it, including calculating yesterday's date, even across month and year boundaries including Leap Year, and localization, etc.
If you really want to get creative, you can call functions in the batch processor... But that's really for a different discussion... :)
Oh, and don't name your batch files .bat either.. They are .cmd's now.. heh..
Hope this helps.
rem set defaults:
set filename1="c:\file1.txt"
set filename2="c:\file2.txt"
set filename3="c:\file3.txt"
rem set parameters:
IF NOT "a%1"=="a" (set filename1="%1")
IF NOT "a%2"=="a" (set filename2="%2")
IF NOT "a%3"=="a" (set filename1="%3")
echo %filename1%, %filename2%, %filename3%
Be careful with quotation characters though, you may or may not need them in your variables.
Late answer, but currently the accepted one is at least suboptimal.
Using quotes is ALWAYS better than using any other characters to enclose %1.
Because when %1 contains spaces or special characters like &, the IF [%1] == simply stops with a syntax error.
But for the case that %1 contains quotes, like in myBatch.bat "my file.txt", a simple IF "%1" == "" would fail.
But as you can't know if quotes are used or not, there is the syntax %~1, this removes enclosing quotes when necessary.
Therefore, the code should look like
set "file1=%~1"
IF "%~1"=="" set "file1=default file"
type "%file1%" --- always enclose your variables in quotes
If you have to handle stranger and nastier arguments like myBatch.bat "This & will "^&crash
Then take a look at SO:How to receive even the strangest command line parameters?

Resources