How to set a variable for the current OS session only

前端 未结 3 558
一整个雨季
一整个雨季 2021-01-14 06:27

setx permanently modifies environment variables.
set only makes variables available during batch script duration.
Is there any way to set a

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-14 07:23

    @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 may work for you. You would need to change the SET instructions hown in CAPS to SETX. 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 having setx it. You could even write a setxX batch to setx then set (or vice-versa) the required variable.

提交回复
热议问题