How to run program or a batch file from Code section of Inno Setup? [closed] - inno-setup

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How can I insert Run (unzip.exe and a batch file) within the Code section instead of Run? I attempted the approach used here Inno Setup: Install other installer and run it before continuing my install but unable to get it to work so I reverted to using the Run section to run two scripts. What I have done so far appears sloppy. The Inno Setup "finished" page displays an option checkbox to run the batch script, whereas I'd prefer it to run automatically before reaching this stage.
[Setup]
PrivilegesRequired=admin
[Files]
Source: "CC.exe"; DestDir: "{pf}\CC"; DestName: "CC.exe"
Source: "bbb.update.zip"; DestDir: "{userdesktop}"; Flags: deleteafterinstall
Source: "unzip.exe"; DestDir: "{userdesktop}"; Flags: deleteafterinstall
[Run]
Filename: "{userdesktop}\unzip.exe"; \
Parameters: "x {userdesktop}\bbb.update.zip -d {userdesktop}"; \
Flags: runascurrentuser nowait
Filename: "{userdesktop}\update.bat"; \
Flags: runascurrentuser nowait postinstall skipifsilent
(the update.bat file cleans up after installing)

Use Exec function. For example in CurStepChanged event function.
Also you need to wrap the paths in command parameters to quotes, in case they contain spaces.
[Code]
procedure CurStepChanged(CurStep: TSetupStep);
var
ErrorCode: Integer;
begin
if CurStep = ssPostInstall then
begin
Exec(
ExpandConstant('{userdesktop}\unzip.exe'),
ExpandConstant('x "{userdesktop}\bbb.update.zip" -d "{userdesktop}"'),
'', SW_HIDE, ewNoWait, ErrorCode);
Exec(
ExpandConstant('{userdesktop}\update.bat'), '', '', SW_HIDE, ewNoWait, ErrorCode);
end;
end;

Related

Generate a configuration file with an entry for each selection using Inno Setup [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Based on what I pick in Inno Setup, the installer should add an entry containing package name followed by , into config.ini
And extract the right premade config files (that are stored in the installer) needed for the few specific setups into the Config folder.
There are plenty of programs like Chrome/Firefox which don't need any parameters or additional configs to install.
Desired config.ini file syntax:
<package1>, <package2 /X /Y /Z>, <package 3> ...
Etc.
Where <packageX> is a string value tied to the checkboxes in the installer selection menu.
After Inno Setup completes, it should run a batch file.
Bonus points: Again.. not only output the config.ini, BUT also extract necessary premade configs set-up for the specific program into a folder C:/NKsetup/Config/
Add each each of your packages as a component to the Components section. Then in the Files section, you can choose what files get installed based on the components selected. For the packages list config file, you need to code that with use of the WizardIsComponentSelected function.
[Setup]
DefaultDirName=C:\some\path
[Types]
Name: "custom"; Description: "-"; Flags: iscustom
[Components]
Name: "sqlserver"; Description: "Microsoft SQL server"
Name: "chrome"; Description: "Google Chrome"
Name: "firefox"; Description: "Mozilla Firefox"
[Files]
Source: "install.bat"; DestDir: "{app}"
Source: "common-config.ini"; DestDir: "{app}"
Source: "sqlserver-config.ini"; DestDir: "{app}"; Components: sqlserver
Source: "browsers-config.ini"; DestDir: "{app}"; Components: chrome firefox
[Run]
Filename: "{app}\install.bat"; StatusMsg: "Installing..."
[Code]
procedure CurStepChanged(CurStep: TSetupStep);
var
ConfigPath: string;
Packages: string;
begin
if CurStep = ssPostInstall then
begin
if WizardIsComponentSelected('sqlserver') then
begin
Packages := Packages + ',sql-server-express /X /Y /Z';
end;
if WizardIsComponentSelected('chrome') then
begin
Packages := Packages + ',chrome';
end;
if WizardIsComponentSelected('firefox') then
begin
Packages := Packages + ',firefox';
end;
// Remove the leading comma
if Packages <> '' then
begin
Delete(Packages, 1, 1);
end;
ConfigPath := ExpandConstant('{app}\config.ini');
// This is not Unicode-safe
if not SaveStringToFile(ConfigPath, Packages, False) then
begin
Log(Format('Error saving packages to %s', [ConfigPath]));
end
else
begin
Log(Format('Packages saved to %s: %s', [ConfigPath, Packages]));
end;
end;
end;

Inno Setup: Error handling in [Run] section [duplicate]

This question already has answers here:
How to force Inno Setup setup to fail when Run command fails?
(4 answers)
Using Process Exit code to show error message for a specific File in [Run]
(2 answers)
Closed 2 years ago.
I've been creating my first installers with Inno Setup and while they work, I want to look into some more profound error handling in case things go south during installation.
Here are the script snippets containing what I have so far. All of this works, questions follow below.
[Components]
Name: "base"; Description: "Install base files needed for this application"; Types: full compact custom; Flags: fixed
Name: "fonts"; Description: "Install Spartan fonts for a correct rendering of the application"; Types: full custom
Name: "updater"; Description: "Create a scheduled task to run the component updater on a daily basis"; Types: full custom
[Tasks]
Name: "update"; Description: "Run the updater after the installation to bring all application files up to date"
[Files]
; Application files
Source: "{#MyAppSourceNetwork1}\{#MyAppExeName}"; DestDir: "{app}"; Flags: ignoreversion; Components: base
Source: "{#MyAppSourceNetwork1}\{#MyAppcfgName}"; DestDir: "{app}"; Flags: ignoreversion; Components: base
Source: "{#MyAppSourceNetwork1}\Source\Componenten_COM\*"; DestDir: "{app}\Componenten_COM"; Flags: ignoreversion recursesubdirs createallsubdirs; Components: base
Source: "{#MyAppSourceNetwork1}\Source\Componenten_RegAsm\*"; DestDir: "{app}\Componenten_RegAsm"; Flags: ignoreversion recursesubdirs createallsubdirs; Components: base
Source: "{#MyAppSourceNetwork2}\*"; DestDir: "{#MyAppLocalFolderLib}\OCXinstaller"; Flags: ignoreversion recursesubdirs createallsubdirs; Components: base
; Updater
Source: "{#MyAppSource}\Updater\*"; DestDir: "{#MyAppLocalFolderLib}\Updater"; Flags: ignoreversion recursesubdirs createallsubdirs; Components: base
[Run]
; Create scheduled task for updater
Filename: "powershell"; \
Parameters: "-Executionpolicy Bypass -NoProfile -WindowStyle Hidden -Command ""Register-ScheduledTask -TaskName '{#MyAppTSUpdaterName}' -Description 'Smartclient component updater' -User System -Action (New-ScheduledTaskAction -Execute wscript -Argument '{#MyAppLocalFolderLib}\Updater\{#MyAppUpdateScript}') -Trigger (New-ScheduledTaskTrigger -Daily -At 07:00) -Settings (New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -DontStopOnIdleEnd -ExecutionTimeLimit (New-TimeSpan -Hours 2) -MultipleInstances IgnoreNew)"""; \
Description: "Create scheduled task for updater"; \
StatusMsg: "Creating scheduled task ""{#MyAppTSUpdaterName}""..."; \
Flags: runhidden; \
Components: updater
; Run scheduled task for updater
Filename: "wscript"; \
Parameters: """{#MyAppLocalFolderLib}\Updater\{#MyAppUpdateScript}"""; \
Description: "Run Smartclient component updater"; \
StatusMsg: "Running Smartclient updater. Please wait, this will take a few minutes..."; \
Flags: runhidden; \
BeforeInstall: SetMarqueeProgress(True); \
AfterInstall: SetMarqueeProgress(False); \
Tasks: update
; Offer option to launch application after installation
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent unchecked
[Code]
// Show infinite progress bar while waiting
procedure SetMarqueeProgress(Marquee: Boolean);
begin
if Marquee then
begin
WizardForm.ProgressGauge.Style := npbstMarquee;
end
else
begin
WizardForm.ProgressGauge.Style := npbstNormal;
end;
end;
For the purpose of testing, I deliberatly wrote some errors in the commands (RRRegister-ScheduledTask / UUUpdater / NNNotepad) and in the log file below, you can clearly see that the commands do not return code 0.
During the installation I got message boxes for the wscript and notepad commands, making clear that something went wrong, with the return code and an OK button. However, the Powershell command doesn't give a message at all. It only returns an error when I write the command wrong (PPPowershell.exe) but not when there is an error in the Parameters flag. Any idea why? Because I'm sure Powershell returns some nice red lines indicating an error occured.
Additionally, I notice that Inno Setup writes in the log that the installation succeeded (7th line in my snippet) although it even still needs to start with the [Run] section. When I write the commands without typos, the setup does everything correctly, but it doesn't give me much confidence in how my installers might indicate success even when some actions didn't succeed. Why isn't the [Run] block considered to be an integral part if the installation?
2020-06-10 08:52:15.025 Saving uninstall information.
2020-06-10 08:52:15.025 Deleting uninstall key left over from previous administrative 32-bit install.
2020-06-10 08:52:15.027 Creating new uninstall key: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall\{C3DAA6E8-7152-40C7-8487-F4A1BDC3EB92}_is1
2020-06-10 08:52:15.027 Writing uninstall key values.
2020-06-10 08:52:15.030 Detected previous non administrative install? No
2020-06-10 08:52:15.030 Detected previous administrative 64-bit install? No
2020-06-10 08:52:15.047 Installation process succeeded.
2020-06-10 08:52:15.052 -- Run entry --
2020-06-10 08:52:15.052 Run as: Current user
2020-06-10 08:52:15.053 Type: Exec
2020-06-10 08:52:15.053 Filename: powershell
2020-06-10 08:52:15.053 Parameters: -Executionpolicy Bypass -NoProfile -WindowStyle Hidden -Command "RRRegister-ScheduledTask -TaskName 'Smartclient Updater' -Description 'Smartclient component updater' -User System -Action (New-ScheduledTaskAction -Execute wscript -Argument 'C:\Smartclient_MH_LIB\Updater\Mediahuis_Smartclient_Components_Updater.vbs') -Trigger (New-ScheduledTaskTrigger -Daily -At 07:00) -Settings (New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -DontStopOnIdleEnd -ExecutionTimeLimit (New-TimeSpan -Hours 2) -MultipleInstances IgnoreNew)"
2020-06-10 08:52:19.509 Process exit code: 1
2020-06-10 08:52:19.511 -- Run entry --
2020-06-10 08:52:19.511 Run as: Current user
2020-06-10 08:52:19.511 Type: Exec
2020-06-10 08:52:19.511 Filename: wscript
2020-06-10 08:52:19.511 Parameters: "C:\Smartclient_MH_LIB\UUUpdater\Mediahuis_Smartclient_Components_Updater.vbs"
2020-06-10 08:57:47.994 Process exit code: 1
2020-06-10 08:57:47.996 -- Run entry --
2020-06-10 08:57:47.996 Run as: Current user
2020-06-10 08:57:47.996 Type: Exec
2020-06-10 08:57:47.996 Filename: NNNotepad
2020-06-10 08:57:47.997 Exception message:
2020-06-10 08:57:47.997 Message box (OK):
Unable to execute file:
NNNotepad
CreateProcess failed; code 2.
The system cannot find the file specified.
2020-06-10 08:57:50.009 User chose OK.
So where should I take this from here to be able to handle the return codes of these commands?
How can I specify which return codes from a [Run] line should be considered fatal, and which not? How do I catch them? I understand I will probably need to write [Code] blocks, maybe using Exec? But how do I trigger them from a [Run] line? Using Check or something else?
Can someone give an example how to catch the return code from the Powershell or Wscript command and how to throw a message box which manipulates the behaviour of the installer (e.g. quit if you click Abort, continue if you click Ignore)?
How do you manipulate the exit code from the setup itself in case things go wrong? Or is this a big no-no?
I read things about Windows process exit codes that are different than return codes in Pascal scripting. This is confusing the hell out of me. Can someone explain?
I've been looking into many examples and similar topics, but couldn't really find a useful case which I could edit to suit my needs.
Thanks for reading this far and for any help / insight you can offer.
EDIT 2020/06/16
Sorry for the delay. Meanwhile the topic has been closed, but I wanted to let you know how I solved it eventually and that I'm grateful for the help you offered. With the suggestions provided by Martin Prikryl and some additional searching I was able to reach my goals: write a [Code] block which lets me perform additional tasks, catch the return code and override the Setup exitcode if I wish to. I will post my generic code example below for anyone who needs a similar solution.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; // Example - Run additional actions purely in the [Code] block during the ssPostInstall step (executed after the [Run] block) and use ExitCode to modify the default exit code of the setup
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
[Tasks]
Name: "runscript"; Description: "Run a script"
[Code]
// Start with exmpty exit code, can be used to override setup exit code with GetCustomSetupExitCode
var
ExitCode: Integer;
// Show infinite progress bar while waiting
procedure SetMarqueeProgress(Marquee: Boolean);
begin
if Marquee then
begin
WizardForm.ProgressGauge.Style := npbstMarquee;
end
else
begin
WizardForm.ProgressGauge.Style := npbstNormal;
end;
end;
// Run post-installation commands
procedure CurStepChanged(CurStep: TSetupStep);
var
ResultCode: Integer;
ProgramNAme: String;
ProgramArguments: String;
begin
if CurStep = ssPostInstall then
begin
// Change progressbar
SetMarqueeProgress(True);
// Run script if task is selected
if IsTaskSelected('runscript') then
begin
WizardForm.StatusLabel.Caption := 'Running script. This may take a few minutes...';
ProgramName := 'wscript';
ProgramArguments := ExpandConstant('{sd}\Smartclient_MH_LIB') + '\script\{#MyAppUpdateScript}';
Log('Running ' + ProgramName + ' ' + ProgramArguments);
if Exec(ProgramName, ProgramArguments, '', SW_HIDE, ewWaitUntilTerminated, ResultCode) then
begin
Log('ResultCode = ' + IntToStr(ResultCode) + '.');
if ResultCode = 0 then
begin
Log('Setup successfully ran the script.')
end
else
begin
Log('Setup failed to run the script.');
ExitCode := ExitCode + 1;
end;
end;
end
else
begin
Log('Skipping update because task "update" is not selected.');
end;
// Change progressbar
SetMarqueeProgress(False);
end;
end;
// Override setup exit code
function GetCustomSetupExitCode: Integer;
begin
if ExitCode <> 0 then
begin
Log('Returning custom exit code ' + IntToStr(ExitCode));
end;
Result := ExitCode;
end;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

InnoSetup : Problem with file check function

I try to make a setup wizard with InnoSetup software to deploy easily my program but I encounter currently a problem with my script.
I am used to make basic setup wizard but now I have to implement a new functionality whose :
I want to check if a file exist on the computer to not overwrite it.
I made like this (in the [files] section):
[Files]
Source: "{#MyAppExeFile}"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#MyAppSrcFolder}*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
Source: "{#MyAppSrcFolder}FileFolder\testFile.py"; DestDir: "D:\Users\{username}\myFolderTest\"; Flags: ignoreversion recursesubdirs createallsubdirs;Check: needInstallFile(ExpandConstant('{username}'))
And i added this following [code] section:
[code]
function needInstallFile(user : string) : Boolean;
begin
if IsTaskSelected('initFile') then begin
if FileExists('D:\Users\' + user + '\myFolderTest\testFile.py') then begin
MsgBox('The file already exist', mbInformation, MB_OK);
Result:=False;
exit;
end else begin
Result:=True;
exit;
end;
end;
end;
When i compile my code, it's work but if the file already exist, i have three popup (and not just one like i would want to have). I DON'T understand despite my researches on Internet.
If you have a lead to help me, I'm interested because i'm stuck.
Thank you in advance for your help.
PS : Sorry for my English, i am unfortunatly a french guy.
Thomas

Inno Setup - Avoid displaying filenames of sub-installers

I am trying to use the idea from Inno Setup - How to hide certain filenames while installing? (FilenameLabel)
The only sure solution is to avoid installing the files, you do not want to show, using the [Files] section. Install them using a code instead. Use the ExtractTemporaryFile and FileCopy functions
But the files that I want to hide are using in the [Run] Section:
[Files]
Source: "_Redist\DXWebSetup.exe"; DestDir: "{tmp}"; Flags: deleteafterinstall
[Run]
Filename: "{tmp}\DXWebSetup.exe"; Components: DirectX; StatusMsg: "Installing DirectX..."; \
BeforeInstall: StartWaitingForDirectXWindow; AfterInstall: StopWaitingForDirectXWindow
How to hide (while installing, in filenamelabel) using [Files] section, ExtractTemporaryFile and FileCopy functions?
The easiest is to give up on the standard [Files] and [Run] sections and code everything on your own in the CurStepChanged event fuction:
[Files]
Source: "dxwebsetup.exe"; Flags: dontcopy
[Code]
procedure CurStepChanged(CurStep: TSetupStep);
var
ProgressPage: TOutputProgressWizardPage;
ResultCode: Integer;
begin
if CurStep = ssInstall then { or maybe ssPostInstall }
begin
if IsComponentSelected('DirectX') then
begin
ProgressPage := CreateOutputProgressPage('Installing prerequsities', '');
ProgressPage.SetText('Installing DirectX...', '');
ProgressPage.Show;
try
ExtractTemporaryFile('dxwebsetup.exe');
StartWaitingForDirectXWindow;
Exec(ExpandConstant('{tmp}\dxwebsetup.exe'), '', '', SW_SHOW,
ewWaitUntilTerminated, ResultCode);
finally
StopWaitingForDirectXWindow;
ProgressPage.Hide;
end;
end;
end;
end;
This even gives you a chance to check for results of the sub-installer. And you can e.g. prevent the installation from continuing, when the sub-installer fails or is cancelled.
Then it's easier to use the PrepareToInstall instead of the CurStepChanged.
Another option is to display a custom label, while extracting the sub-installer.
See Inno Setup - How to create a personalized FilenameLabel with the names I want?

How to get Inno Setup to unzip a file it installed (all as part of the one installation process)

To save bandwidth/space as well as prevent accidental meddling, the installation files for a database product (call it Ajax), have been zipped up (call that file "AJAX_Install_Files.ZIP). I would like to have Inno-Setup "install" (i.e., copy) the AJAX_Install_Files.ZIP file to the destination, and then Unzip the files into the same folder where the .ZIP file is located. A subsequent program would be fired off by Inno Setup to actually run the install of product "Ajax".
I've looked through the documentation, FAQ, and KB at the Inno Setup website, and this does not seem possible other than writing a Pascal script (code) - would that be correct, or are there are any alternative solutions?
You can use an external command line tool for unzipping your archive, see here for example. Put it in your [Files] section:
[Files]
Source: "UNZIP.EXE"; DestDir: "{tmp}"; Flags: deleteafterinstall
Then call it in your [Run] section, like this:
[Run]
Filename: "{tmp}\UNZIP.EXE"; Parameters: "{tmp}\ZipFile.ZIP -d C:\TargetDir"
(You'll probably want to take your target directory from a script variable, so there is some more work that needs to be done)
You can use the shell Folder.CopyHere method to extract a ZIP.
const
SHCONTCH_NOPROGRESSBOX = 4;
SHCONTCH_RESPONDYESTOALL = 16;
procedure UnZip(ZipPath, TargetPath: string);
var
Shell: Variant;
ZipFile: Variant;
TargetFolder: Variant;
begin
Shell := CreateOleObject('Shell.Application');
ZipFile := Shell.NameSpace(ZipPath);
if VarIsClear(ZipFile) then
RaiseException(
Format('ZIP file "%s" does not exist or cannot be opened', [ZipPath]));
TargetFolder := Shell.NameSpace(TargetPath);
if VarIsClear(TargetFolder) then
RaiseException(Format('Target path "%s" does not exist', [TargetPath]));
TargetFolder.CopyHere(
ZipFile.Items, SHCONTCH_NOPROGRESSBOX or SHCONTCH_RESPONDYESTOALL);
end;
Note that the flags SHCONTCH_NOPROGRESSBOX and SHCONTCH_RESPONDYESTOALL work on Windows Vista and newer.
For an example of extracting some files only, see:
How to get Inno Setup to unzip a single file?
I answered a very similar question and some of the details apply.
I would question why you need a ZIP file of the contents? I personally would place the uncompressed files into the setup. I would then have two [category] entries one for the application and one for the data. Default both the be checked.
This would allow the users to install a fresh set of the data if needed at a later date.
If you really want a ZIP file and want to keep it easy you could, ship both the zip files and the uncompressed files in the same setup.
Update:
By default files that get placed in your setup.exe are compressed.
You can also have the files extracted to a temporary location so you can run your
installation application, then have them deleted.
[Files]
Source: "Install1.SQL"; DestDir: "{tmp}"; Flags:deleteafterinstall;
Source: "Install2.SQL"; DestDir: "{tmp}"; Flags:deleteafterinstall;
You can just create silent self-extracting archive (SFX) archive, example described here how to create SFX archive for stuff you need, and write Pascal code to just run it like this (script for Inno Setup 6.0.2):
[Tasks]
Name: "intallSenselockDriver"; Description: "Install Senselock driver."; GroupDescription: "Install the necessary software:";
[Code]
function ExecTmpFile(FileName: String): Boolean;
var
ResultCode: Integer;
begin
if not Exec(ExpandConstant('{tmp}\' + FileName), '', '', SW_SHOWNORMAL, ewWaitUntilTerminated, ResultCode)
then
begin
MsgBox('Other installer failed to run!' + #13#10 + SysErrorMessage(ResultCode), mbError, MB_OK);
Result := False;
end
else
Result := True;
end;
procedure RunOtherInstallerSFX(ArchiveName: String; ExePath: String);
begin
ExtractTemporaryFile(ArchiveName);
ExecTmpFile(ArchiveName);
ExecTmpFile(ExePath);
end;
function PrepareToInstall(var NeedsRestart: Boolean): String;
begin
if WizardIsTaskSelected('intallSenselockDriver') then
RunOtherInstallerSFX('1_senselock_windows_3.1.0.0.exe', '1_senselock_windows_3.1.0.0\InstWiz3.exe');
Result := '';
end;
It worked perfectly for me.
Using Double quotes worked for me.
Single quotes were not working.
[Files]
Source: "unzip.exe"; DestDir: "{userappdata}\{#MyAppName}\{#InputFolderName}"; Flags: ignoreversion
[Run]
Filename: "{userappdata}\{#MyAppName}\{#InputFolderName}\unzip.exe"; Parameters: " ""{userappdata}\{#MyAppName}\{#InputFolderName}\ZIPFILENAME.zip"" -d ""{userappdata}\{#MyAppName}\{#InputFolderName}"" "; Flags: runascurrentuser

Resources