Invoking NSIS run-time commands on compile-time

From NSIS Wiki
Jump to navigationJump to search
Author: Afrow UK (talk, contrib)


Description

It's a common question nowadays for people to ask "how can I use a run-time command on compile-time". For example, someone may want to get the version of a local file and use that version in a !define, or perhaps someone may want to do some string manipulation and place the result in the installers' caption!

This example was written for kiplingw in this forum topic. It gets the version (#.#.#.#) of C:\MyFile.exe and puts it into a !define which you can then use anywhere in your script.

The Script

Firstly, create the below script as GetVersion.nsi in the same directory of your main script. Make sure you change the path of "C:\MyFile.exe" to a suitable .exe or .dll path. (Note that you should use the !getdllversion preprocessor command instead of this example if you want to achieve the same)

!define File "C:\MyFile.exe"
 
OutFile "GetVersion.exe"
SilentInstall silent
RequestExecutionLevel user ; don't write $EXEDIR\Version.txt with admin permissions and prevent invoking UAC
 
Section
 
 ## Get file version
 GetDllVersion "${File}" $R0 $R1
  IntOp $R2 $R0 / 0x00010000
  IntOp $R3 $R0 & 0x0000FFFF
  IntOp $R4 $R1 / 0x00010000
  IntOp $R5 $R1 & 0x0000FFFF
  StrCpy $R1 "$R2.$R3.$R4.$R5"
 
 ## Write it to a !define for use in main script
 FileOpen $R0 "$EXEDIR\Version.txt" w
  FileWrite $R0 '!define Version "$R1"'
 FileClose $R0
 
SectionEnd

Put this in your main script:

!makensis "GetVersion.nsi"
!system "GetVersion.exe"
!include "Version.txt"
; optional cleanup
!delfile "GetVersion.exe"
!delfile "Version.txt"

Now you shall have the ${Version} define available which you can use anywhere in your script (e.g. to go in your BrandingText or OutFile name)...

OutFile "MySoftware-${Version}.exe" # could be "MySoftware-0.1.2.3.exe"

-Stu

Linux/Unix way for running commands on compile time

Note! Only works under Unix and Linux! Compile this script first: (replace /home/you/scripts/nsis/hello.sh with a path to what your installer will be at)

OutFile "RunCmdOnCompile"
SilentInstall silent
 
Function WriteScript
 FileOpen $R0 "/home/you/scripts/nsis/hello.sh" w
  FileWrite $R0 '"#!/bin/sh'
  FileWrite $R0 'echo "Hello world!"'
  FileWrite $R0 "sleep 500"
 FileClose $R0
FunctionEnd
 
Section 
Call WriteScript
SectionEnd

Now in the real installer, put these lines first before anything:

!system "RunCmdOnCompile"
!system "hello.sh"