Search code examples
windowsinstallationnsis

Getting currently logged on user when running as admin


I've written an installer using NSIS and I need it to install some files (DLLs etc.) in a standard location like C:/Program Files/App Name/. I also need to install files in the current user's Application Data directory. The problem is that when the user is not an admin on Vista I need to elevate privileges and in doing so the environment variables change so the current user now appears to be the admin user and I end up installing in the Admin user's directory instead of the actual user. You have to elevate when you start the installer so I can't grab the username and then elevate. Is there some reasonable way to figure out who the actual user is when I'm running an installer as an admin?

Edit: Unfortunately having the data copied on first run is not an option. The app won't work without the thing I'm writing to the user's directory because it's a MS Word template. My stuff WOULD NOT RUN without the template, so I MUST write the template on install and Word requires the template to be in the user's AppData dir.


Solution

  • All of my NSIS installers use this UAC plug-in: http://nsis.sourceforge.net/UAC_plug-in.

    You can elevate to admin as soon as you launch the installer. This spawns a second instance of your installer that does all of the work. But you can make calls to code segments that will run in the original process as the user that launched the installer.

    So you could have an installer section like so:

    Section "Install My Program" SecMain
        ...    
        # Install files to common folders
        ...
        !insertmacro UAC.CallFunctionAsUser CopyUserWordTemplate
        ...
    SectionEnd
    
    Function CopyUserWordTemplate
        SetOutPath $LOCALAPPDATA
        File "MyWordTemplate.dot"
    FunctionEnd