How to set a variable for the current OS session only

前端 未结 3 591
一整个雨季
一整个雨季 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条回答
  •  萌比男神i
    2021-01-14 07:18

    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:

    @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 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.

提交回复
热议问题