Search code examples
powershellnsis

How to cancel NSIS Installer after executed powershell script was canceled?


For my software suite I created an installer with NSIS. This installer includes a powershellscript with a GUI. I want to cancel the installation process after the user has clicked the cancelbutton in the powershell gui.

The script creates a powershell gui with a listbox. The listbox-item will be written in a txt-file. There are two buttons: One for OK - to write the item in the file, the other button is a cancel button. After the ok-button was clicked, the second form opens.

Some code snippets from the powershellscript:

$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel

if('Ok' -eq $form.ShowDialog())
 {
   $msg = "Item copied to txt-file"
   [System.Windows.Forms.MessageBox]::Show($msg,"Confirmation",0)
 }

With this instruction I call the PS-Script in NSIS:

ExecWait "powershell -ExecutionPolicy Bypass -WindowStyle Hidden -File nameofscript.ps1 -FFFeatureOff"

Solution

  • If you return an exit code from your PowerShell on cancel, you can handle that from the NSIS script:

    Powershell:

    if ($form.ShowDialog() -eq [System.Windows.Forms.DialogResult]::Cancel)
    {
        exit 1
    }
    

    NSIS:

    ClearErrors
    ExecWait "powershell -ExecutionPolicy Bypass -WindowStyle Hidden -File nameofscript.ps1 -FFFeatureOff"
    IfErrors 0 noError
    ; Handle error here
    noError:
    

    See also: how to get the exit code of other application in nsis