How to set a variable for the current OS session only
setx
constantly changing environment variables. set
only makes variables available during batch script duration.
Is there a way to set a variable to keep its value until the system restarts?
For example. in my batch file, I check if the variable is set like this:
if %MYVAR% == 1 (
<block>
)
source to share
@ECHO Off IF NOT EXIST q25244121.org GOTO done :: reset to original FOR /f "tokens=1*delims==" %%a IN (q25244121.org) DO ( IF DEFINED %%a FOR /f "tokens=1*delims==" %%p IN ('set %%a') DO ( IF "%%a"=="%%p" IF "%%b" neq "%%q" SET "%%a=%%b" ) ) :: Delete if not originally defined FOR /f "tokens=1*delims==" %%p IN ('set') DO ( FINDSTR /L /i /c:"%%p=" q25244121.org >NUL IF ERRORLEVEL 1 SET "%%p=" ) :done :: Record current settings set>q25244121.org EXIT /b
This might work for you. You will need to change the instruction SET
in CAPS to SETX
. The tempfile should of course also be placed in a file where the username is part of the name you used.
If you included this batch in your startup directory, then it should restore the last saved environment variables.
So, the first time you log in, the values ββof the current variables are saved. On subsequent logins, the environment will be restored to the last saved environment, regardless of whether it was executed SETX
.
However, you will need to change the procedures. This will restore to a known state. If you really wanted to SETX
specify a value or install some software that adds new values ββto environment variables or changes to existing ones ( PATH
will be a favorite here), then you need to run this procedure first, make changes, delete save the file, and rerun this procedure. It's embarrassing, I admit, but this is the way to do it.
Oh - and remember SET
your variable after SETX
. You can even write the package setxX
to SETX
and then SET
(or vice versa) the variable you want.
source to share
You can do this via a Batch-JScript script hybrid that uses JScript WshShell.Environment. The documentation states that there are four types of environments: system, user, volatiles and processes, and the volatile type "Applies to the current login session and does not persist between exits and restarts", this is exactly what you want:
@if (@CodeSection == @Batch) @then
@echo off
rem Define a persistent variable for the current OS session only via JScript
Cscript //nologo //E:JScript "%~F0" MYVAR "This is the value"
goto :EOF
@end
var colEnvVars = WScript.CreateObject("WScript.Shell").Environment("Volatile");
colEnvVars(WScript.Arguments(0)) = WScript.Arguments(1);
You should save the previous code in a .bat file and execute it like any batch file. Note that a variable defined this way is not available in the current cmd.exe window, but only in future cmd.exe windows open in the same OS session.
Tested on Windows 8.1.
source to share