Assign empty system variable using setx - batch-file

I need a system variable and assign an empty string value to it. I've tried
setx samplepassword ""
But upon echo %samplepassword% , what should be an empty string is instead %samplepassword%. Now I found this in the docs
Setting value of "" (empty quotes) will appear to delete the variable
- it's not shown by SET but the variable name will remain in the registry.
http://ss64.com/nt/setx.html
How can I assign an empty system variable using setx?
Update:
I have checked the environment variables via the Windows GUI: Control Panel | System | Advanced | Environment Variables and saw that the DB_PASSWORD was indeed initialized with an empty string value. But why does executing echo %samplepassword% give me the above output? I have opened a new instance of cmd to be precise.

Technically you can create an empty environment variable, but not with setx.
Run that as administrator
reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment" /v TESTENV /d ""
the registry key is added:
it even shows in environment variables system panel
But not in the list when invoking set
So even if it is possible, it is rather useless. However it could fool some programs testing if the env. variable exists by checking if registry key exists. So it could even be counter-productive and source of confusion.

I think you have a misconception here. There is no way to assign an
"empty string" to an environment (Batch) variable. The command set
"samplepassword=" deletes the variable, so echo "%samplepassword%"
just show "". You don't need setx command to do that, nor setx can
modify this behavior. – Aacini Aug 9 at 4:39
TL;DR: Technically it is not possible to create an empty variable in the environment. – Aacini

I had the same problem getting a file name with or without a suffix. You can work around this with a string prefix and string extraction (see here), e.g.
not empty string:
set COUNT=two
set SUFFIX=?s
echo %COUNT% thing%SUFFIX:~1%
gives two things
empty string
set COUNT=one
set SUFFIX=?
echo %COUNT% thing%SUFFIX:~1%
gives one thing
With the %SUFFIX:~1% you dismiss the string prefix (in this example ?) and get the rest of the string. This rest can be empty.

Related

Why isn't my env variable passed to subscript in my bat script

I have 2 scripts:
testEnv.bat:
set TEST_VAR = "hello"
call testEnvSub.bat
testEnvSub.bat:
echo %TEST_VAR%
When I run testEnv.bat, I just get:
"ECHO is on"
So clearly the env variable I set in testEnv isn't being passed to subscript. How do I get it to pass correctly?
Question: "So clearly the env variable I set in testEnv isn't being passed to subscript."
Answer: Not at all, the variable is created, you're just not calling the correct variable name, because you created it incorrectly.
Question: "How do I get it to pass correctly?"
Answer: Unlike C+, Perl etc. Windows cmd actually uses the whitespace as part of the variable name and value. So in fact, you created a variable called %TEST_VAR % instead of %TEST_VAR% and have a value of "hello" including the leading whitespace.
So give this a go, note the double quotes starts before the variable name and closes after the value to eliminate whitespace creep.
#echo off
set "TEST_VAR=hello"
call testEnvSub.bat
Also, not that it makes much difference in execution, try and name your batch files with the .cmd extension instead of .bat it is sort off old fashioned.

Batch environement variables woes

I have no problem with process-level variables, such as:
Set a=ABC
Echo '%a%'
> 'ABC'
And I understand why persistent variables, being set in the registry (at one of three possible locations), are not available in the current session:
Setx a=ABC
Echo '%a%'
> '%a%'
[Open a new command window:]
Echo '%a%'
> 'ABC'
This works the same when the first portion is in a script, and the last two lines occur in a Command window (cmd). However, when I set (setx) a persistent variable in a script, and then run another script to read it, the results are wildly unpredictable to me. For instance, the first time I run the following script, I expect it to set the variable (but not Echo it), while on all subsequent runs, since the variable is set previous to calling the script, %a% should have the value ABC:
Echo '%a%'
Setx a ABC
Echo '%a%'
Pause
Unfortunately, even on the second run both Echo statements return an empty value (''). A new command window will return the expected value ('ABC'), as I noted before.
To make things worse for me, SOMETIMES I can access a previously stored variable's value - but then I can't change it. I suspect that in these instances I am accessing the variable from another environment (System vs User vs Machine), but I can't seem to understand this.
Why can I not access the persistent variable from a script? How should I be writing the script so it can?
When initiating from cmd the help. setx /? a specific area specifies:
NOTE: 1) SETX writes variables to the master environment in the registry.
2) On a local system, variables created or modified by this tool
will be available in future command windows but not in the
current CMD.exe command window.
You therefore need to close the current cmd window and start a new instance in order to load the new or modified environment variable from the master environment.
However as per your comments you simply want to store the environment variables once off for other scripts to access. therefore this:
if not defined aa setx aa ABC & exit
echo %aa%
pause
when you run it the first time, will set the variable and exit, if the variable is not yet defined, when you run the script the second time, it will not set it, as it now finds the variable exists.
if however you want to do something in the script the first time it is run as well with variable %aa% then simply set the temp variable as well.
if not defined aa setx aa ABC & set aa=ABC
echo %aa%
pause
So first time you run the above, it will set a locally and in the environment, but the 2nd time you start it, it will skip the first line as %a% is found in the environment.
We can then look at editing existing variables as well:
if not defined aa setx aa ABC & set "aa=ABC"
if not "%aa%" == "NEW_VALUE" setx aa NEW_VALUE & set "aa=NEW_VALUE"
echo %aa%
pause
Same principal, but now we check the value as well to see if it contains the modified value required.

Batch "SET" command

I keep seeing "set y=%y:~0,-2%" or some visual equivalent to it in code, but I have no idea what it's called, what it does, or how it's syntax works; I haven't been able to find an explanation, just more uses of it. Can some one explain?
"Set" sets the value of a Windows variable.
EX: set myvar=abc <= assigns the string "abc" to variable "%myvar"
"%" deferences the current value of a Windows Variable.
EX: echo %myvar% <= prints "abc"
The %y:~0,-2 syntax extracts a substring from the current value of the variable
<= extracts last 2 characters from Windows variable "%y"
Here are some useful links that might help :
Tricks with Command Line Arguments
Command line Parameters
Variable substitution
Set is used to set variables eg.: set /p A= will ask the user for input.
in cmd type set /?

Batch File: Output variable to text file

I would like to output a variable to a text file. I have done this in my code, but I have one output within an if statement that I can't get to work.
if not exist "%TuningLog%" (
set Title=Tuning Parameters Saving Log
set LogTitle=--------- %Title% ---------
echo %LogTitle%>> "%TuningLog%"
)
All its supposed to do is check first for the existense of a log file and if it doesn't exist then I want to in the first instance append a title.
But all I get in the log file is " echo is off." If I don't use a variable and just place text there then it works fine.
Can anybody spot the problem? Thanks for reading and for any help!
UPDATE:
I changed my code to. I don't know much about delayed expansion, but I tried this and it happened to work...
if not exist "%TuningLog%" (
setlocal enabledelayedexpansion
set Title=Tuning Parameters Saving Log
set LogTitle=--------- !Title! ---------
echo !LogTitle!>> "!TuningLog!"
endlocal
)
If anyone can provide a reason as to why the first attempt didn't work and this did, then please inform this thread for the purposes of learning. Thank you!
because or early expansion. your variable gets replaced with its value at the moment the block starts. at this time, it is still undefined and thus empty. if you have echo on, you can watch this happening on screen. if you enable delayed expansion, as you did in your second example, it gets only expanded at the moment it is used, so it works as you expect variables to work in "real" programming languages.
EnableDelayedExpansion
causes Variables to be expanded in simple language it causes the system to treat the value of variable and not the variable name itself

how to clear a variable which is set from command line by "set /p var1="

In Windows batch files, I accept variable from user input by set /p var1=, after var1 is used, I don't know how to reset/clear its value.
If I don't reset/clear its value, when user meets set /p var1= again, and user enter directly. the previous input value will be still there. I don't want it, How to reset it for new user input?
To clear a variable, regardless how it was set:
set "var1="
rare issue, but you can try this:
set "var=%var*=%"
Different answers to original question were already provided above. One additional hint: within batch-script you can use the scopes:
setlocal
...
endlocal
This ensures that the variables are only accessible within your batch script and not affecting variables outside of your batch script (i.e. your variables are also not accessible outside of the batch script). By exiting of the batch script - the variables used locally get automatically "cleared".

Resources