nsis

NSIS: Failing to Read Environmental Variable Set with Setx During Compile Time


For the following script:

!define API_LOCAL_SETUP_LOCATION "C:\Temp\Some.exe"

Function API_CHECK
  !system 'for %a in (${API_LOCAL_SETUP_LOCATION}) do setx x1 "%~ta"'
  !if "$%x1%" == "${U+24}%x1%"
    !echo "%x1% not set"
  !else
    !echo "IS SET!"
  !endif
FunctionEnd

The idea is to check the "Date Modified" file of the "C:\Temp\Some.exe" file and store the value in the x1 environmental variable during compile time.

Before compiling the NSIS script, if I execute set in Command Prompt, no x1 environment variable exists (i.e., not listed).

If I compile the NSIS script, the following is logged by the compiler:

...
!define: "API_LOCAL_SETUP_LOCATION"="C:\Temp\Some.exe"
Function: "API_CHECK"
!system: "for %a in (C:\Temp\Some.exe) do setx x1 "%~ta""

C:\Users\User\Documents\Project\Installer>setx x1 "02/16/2024 01:10 PM" 

SUCCESS: Specified value was saved.
!system: returned 0
%x1% not set (Configuration.nsh:39)

BUT, if I open up a new Command Prompt window and execute set command, x1 environment variable is present and is assigned to "02/16/2024 01:10 PM" as such: x1=02/16/2024 01:10 PM


So, why can't I read x1 environment variable during compile time?

NOTE: I am trying to avoid setting the environment variable as a system variable (i.e., setx /m).


Solution

  • Existing processes do not pick up changed environment variables, only Explorer does. New processes you start from Explorer will have the new variable.

    Do the !system+!include trick to get something into NSIS at compile-time:

    !define API_LOCAL_SETUP_LOCATION "$%windir%\Explorer.exe"
    
    !tempfile TMPINC
    !system 'for %a in (${API_LOCAL_SETUP_LOCATION}) do @echo !define MYDATE "%~ta" >"${TMPINC}"'
    !include "${TMPINC}"
    !delfile "${TMPINC}"
    !error "The date is ${MYDATE}"