Temporarily set environment variables to run the program (exe)

Page creation date :

About the operation of general environment variables

Environment variables that are part of the Windows mechanism can be shared and used by all programs across Windows, and you can set them before you set them before using them. In most cases, it is set from scratch or when you install various programs.

However, because environment variables set as Windows systems are held on a per-computer basis or on a per-logged-in user basis, For programs that require temporary use of environment variables, you want to avoid making changes to locations that affect the entire system.

Set environment variables that can only be used while the program is running

It is for client apps such as batches and tools to use locally. By going through a bat file, you can set environment variables that can only be used within the program.

For example, suppose you want to use an environment variable called in a console TEST_VALUE app. OSFor , 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, it is OK to put environment variables in the visual studio project debug settings in advance.

To temporarily set environment variables when exe is created and run on its own, you can set the environment variables via the bat file. Create a bat file with text, such as: The character code should be Shift-JIS.

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

rem プログラム起動
EnvironmentVariableGet.exe

You can use the set command to keep values in environment variables. This value is valid until the running bat is terminated or until the application started in bat is terminated.

When you start the bat file, you can verify that the environment variable is set.