2

Goal: from my application I want to launch arbitrary commands, e.g. cmd.exe with the current environment variables, e.g. while my application runs and the user modifies the path, launching the terminal should get the new path.

According to my understanding, if a process is launched, it will receive the environment variable values from its launching process (either inherit or individual values). On Windows it is possible to access the latest values of environment variables by reading registry entries (see question "Where are environment variables stored in registry?"). They are stored in the registry as they are configured, e.g. Comspec: %SystemRoot%\system32\cmd.exe. Hence you will need the value of other environment variables like SystemRoot to expand them.

Unfortunately, when taking a look at all environment variables my process received from the parent process with the ones I can read from the registry, there seems to be a large difference. I just can't use the inherited environment variables and replace the registry-configured ones with their values, because then a custom environment variable that the user deleted during the runtime of my application would prevail.

Where can I find out which environment variables Windows by default provides, e.g. SystemRoot?

Thomas S.
  • 5,804
  • 5
  • 37
  • 72

1 Answers1

2

CreateEnvironmentBlock WINAPI can be used to obtain the current environment variables. Its bInherit parameter lets you choose whether to inherit variables from your process or not.

C++ snippet that demonstrates it:

HANDLE userToken = 0;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &userToken))
{
    _tprintf(_T("ERROR: OpenProcessToken"));
    return 1;
}

void* envVars = 0;
if (!CreateEnvironmentBlock(&envVars, userToken, TRUE))
{
    _tprintf(_T("ERROR: CreateEnvironmentBlock"));
    return 1;
}

const wchar_t* iter = (const wchar_t*)envVars;
while (*iter)
{
    _tprintf(_T("ENV: %s\n"), iter);
    iter += _tcslen(iter) + 1;
}

DestroyEnvironmentBlock(envVars);
Codeguard
  • 7,787
  • 2
  • 38
  • 41
  • In case somebody stumbled here looking for a way to get all environment variables active right now in the current process: use `GetEnvironmentStrings()`. – Lassi Dec 04 '19 at 23:18