Run the program (exe) with temporary environment variables set

Page updated :

About the operation of common environment variables

The environment variables provided by Windows can be shared and used by all programs throughout Windows, and you will use them before you set them before you set them. In most cases, it is set from the beginning or when you install various programs.

However, environment variables set as Windows systems are maintained on a per-computer or per-logged-in user basis. For programs that need to use environment variables that are only used temporarily, you should avoid changing them to places that affect the entire system.

Set up an environment knitting nest that can only be used while the program is running

It will be for client apps such as local batches and tools. you can set environment variables that can only be used in the program by going through the bat file.

For example, TEST_VALUE suppose you want to use an environment variable called in a console app. OS PATHEXT , is an environment variable defined from the beginning in Windows.

static void Main(string[] args)
{
  Console.WriteLine("■環境変数");

  Console.WriteLine($"OS         = {Environment.GetEnvironmentVariable("OS")}");
  Console.WriteLine($"PATHEXT    = {Environment.GetEnvironmentVariable("PATHEXT")}");
  Console.WriteLine($"TEST_VALUE = {Environment.GetEnvironmentVariable("TEST_VALUE")}");

  Console.WriteLine("いずれかのキーを押して終了してください。");
  Console.ReadKey();
}

If you want to debug in Visual Studio, you can specify environment variables in the debug settings of your Visual Studio project in advance.

To temporarily set environment variables when you create an exe and run it alone, you can set the environment variables through the bat file. Create a bat file with text similar to the following: The character code should be Shift-JIS.

@echo off
rem 環境変数をセット
set TEST_VALUE=セットした値

rem プログラム起動
EnvironmentVariableGet.exe

You can use the set command to put a value in an environment variable. This value remains in effect until the bat you are running or until the application that you started in bat ends.

you can verify that the environment variables are set by starting the bat file.