setx
permanently modifies environment variables.
set
only makes variables available during batch script duration.
Is there any way to set a variable in order to hold its value until the system is restarted?
E.g. in my batch file, I'm checking if the variable is set like this:
if %MYVAR% == 1 (
<block>
)
This may work for you. You would need to change the
SET
instructions hown in CAPS toSETX
. The tempfile would no doubt also need to be placed in a file where the username is part of the name you'd use.If you were to include this batch in your startup directory, then it should restore the last-saved environment variables' values.
So, on first logon, the current variables' values are stored. On subsequent logons, the environment would be restored to those last stored, regardless of whether a
setx
had been executed.You would however need to change procedures. This will restore to a known state. If you actually wanted to
setx
a value or install some software which adds new environment-variable values or changes existing ones (PATH
would be favourite here) then you'd need to run this routine first, make the changes, delete the save file and re-run this routine. Awkward, I'll admit - but it's a way to do it.Oh - and remember to
set
your variable after havingsetx
it. You could even write asetxX
batch tosetx
thenset
(or vice-versa) the required variable.Ok I found a much simpler (and obviously less hacky) way than the JScript method, but it put us in the right direction with the volatile environment manipulation.
Simply use the
reg
command to manipulate the volatile environment in the registry :reg add
both can create and update the value.\f
bypasses the overwrite confirmation.Setting an empty data with
\d ""
is equivalent to deleting the global variable. You won't see it in the shell withset
, but you can still see it being empty in the registry.Here is a reference: https://ss64.com/nt/reg.html
You may do that via a Batch-JScript hybrid script that use JScript's WshShell.Environment method. The documentation specify that there are four types of environments: System, User, Volatile and Process, and that Volatile type "Applies to current logon session and is not saved between logoffs and restarts", that is exactly what you want:
You must save previous code in a .bat file and execute it as any Batch file. Note that the variable defined this way is not available in the current cmd.exe window, but only in future cmd.exe windows opened in the same OS session.
Tested on Windows 8.1.