Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persist an environment variables after app exits

Is it possible to persist an environment variable in a console application which is available after the process has exited.

I want a console application to set a string which is available to the batch file which executed it.

The console application is in dotnet.

like image 915
benPearce Avatar asked Dec 13 '22 04:12

benPearce


2 Answers

You can use Environment.SetEnvironmentVariable:

Environment.SetEnvironmentVariable("SomeVariable", "Some value", EnvironmentVariableTarget.User);

The last parameter will determine the scope and lifetime of the variable (either Process, User or Machine). If you want to set the variable for the machine you will need to run as admin.

Edit: I do notice though that if executing a console application with the above code, the environment variable is not available until you open a new command window (so if executing the console app from a batch file, the variable will not be available to the batch file, unless there is a trick to have it refresh the set of environment variables that it sees).

Edit 2: OK, I was digging around with this and there seem to be no obvious way to have the batch file get a refreshed set of environment variables. One workaround that I found is to to have the .net code write a batch file for setting the variables, instead of setting them itself. The calling batch script can then run the created batch file to have the environment set up:

.Net Console App:

static void Main(string[] args)
{
    string outputFile = @"c:\temp\setvars.bat";
    string variable = "set SomeVariable=Some value";
    File.WriteAllText(outputFile, variable);
}

BAT-file:

call myconsoleapp.exe
call c:\temp\setvars.bat
echo %SomeVariable%
like image 56
Fredrik Mörk Avatar answered Dec 31 '22 20:12

Fredrik Mörk


This is similar to Xiaofu's, except that you might want to skip the text file altogether and have your program write the data to the console. Put ticks around the program name to have the batch file execute it and use the output, like this:

for /f "tokens=1,2 delims=," %%a in ('MyProgram.exe') do (
    set %%a=%%b
    set %%a=%%b
)

If you want to output other lines of text that should be ignored, then you could add a filter inside the for-loop.

like image 30
Neil Avatar answered Dec 31 '22 20:12

Neil