Search code examples
permissionswindows-installernsisadministratornssm

how to run a program on start up as an administrator using NSIS and NSSM?


I am using nsis to create installer for windows and I am using NSSM to run the application.

everything is fine when I install my server , but the problem my server needs to run as admin in order to use some functionalities. I solved my problem by manually going to "services" then Logon tab to enter my username and password. enter image description here

However , I do not want to do that, I want the installer to ask the user to enter his admin credentials right after installing or before installing.

thanks in advance for your time and efforts


Solution

  • According to their documentation, NSSM already knows how to set service credentials so all you need is the custom page to tie it all together:

    !include LogicLib.nsh
    !include nsDialogs.nsh
    
    !define MYSERVICE "FooBarBaz"
    Var SvcUser
    Var SvcPass
    
    Page Directory
    Page Custom MyServiceCredCreate MyServiceCredLeave ": Service credentials "
    Page InstFiles
    
    Function MyServiceCredCreate
    nsDialogs::Create 1018
    Pop $0
    ${IfThen} $0 == error ${|} Abort ${|}
    ${NSD_CreateLabel} 0 0 100% 12u "Username:"
    Pop $0
    ${NSD_CreateText} 0 13u 100% 12u "$SvcUser"
    Pop $1
    ${NSD_CreateLabel} 0 26u 100% 12u "Password:"
    Pop $0
    ${NSD_CreatePassword} 0 39u 100% 12u "$SvcPass"
    Pop $2
    nsDialogs::Show
    FunctionEnd
    
    Function MyServiceCredLeave
    ${NSD_GetText} $1 $SvcUser
    ${NSD_GetText} $2 $SvcPass
    ${If} $SvcUser == ""
      MessageBox MB_ICONSTOP "Must provide a username!"
      Abort
    ${EndIf}
    FunctionEnd
    
    Section
    SetOutPath $InstDir
    File "myservicething.exe"
    File "nssm.exe"
    nsExec::Exec '"$InstDir\nssm.exe" install "${MYSERVICE}" "$InstDir\myservicething.exe"'
    Pop $0
    nsExec::Exec '"$InstDir\nssm.exe" set "${MYSERVICE}" ObjectName $SvcUser "$SvcPass"'
    Pop $0
    SectionEnd