Defined environment variables in .bat aren't assigned if we launch an administator-required application

The following problem appears only on Windows 10 and not on Windows 7.

I have an app (C++, Visual studio 2017), that requires administrator rights (flag /level='requireAdministrator' on the Linker). Here, I try to get environment variable RESOURCES:

Sample

  int main() {
  const char* buf;
  buf = getenv("RESOURCES");
  if (buf)
      cout << buf << endl;
  else
      cout << 0 << endl;

  system("pause");

  return 0;
}

On Windows 7, I used the following batch file without running it as administrator:

@echo off

set WORKING_DIR=%~dp0
set APP=%WORKING_DIR%\ConsoleApplicationTest.exe
set RESOURCES=%WORKING_DIR%\resources

start "" "%APP%"

As a result - on Windows 10 RESOURCES variable in the c++ code is empty, on the Windows 7 - correct path to the resources. Is the only solution on Windows 10 to launch the batch file as admin always?

728x90

1 Answers Defined environment variables in .bat aren't assigned if we launch an administator-required application

Your problem is that if the cmd instance running the batch file is not elevated, but your executable file requires elevation then the Application Information Service/UAC processes will handle the new process creation and will not transfer the cmd environment block (more here and here).

So, without changing the program code you only have two options: execute the cmd instance as administrator or set the variable as a system environment variable (yes, that requires an elevated process)

4 months ago