Dilshad Abduwali
Dilshad Abduwali

Reputation: 1458

How to exit chocolatey installation if a condition is not met?

In my usual PowerShell scripts, as usual, I use Exit 1 to exit the scripts while I am doing normal sanity checking, so if a condition is not met, I exit early and notify the user to fulfill the condition.

Is Chocolatey package development following the same PoSh way? Or is there any Chocolatey way, such as helpers or core-extension that does this for the developers? for example:

I want the user to provide SQL Server iso path for my SQL Server chocolatey package --params "/IsoPath:C:\Pkg", if no path is provided the package installation should fail:

$pp = Get-PackageParameters
if (!pp['IsoPath']) {
   Write-Host "No 'ISO' path is provided, please provide path in '--params'"
   Exit 1
}

Does the above snippet work to fail the installation or is there any chocolatey way to do this?

Upvotes: 3

Views: 764

Answers (1)

Gary Ewan Park
Gary Ewan Park

Reputation: 18951

There are a couple ways that you can do this.

The first would be to simply throw an exception. A good example of that is in the vcredist140 package, where it decides on whether this package is intended to be used on the OS it is currently being installed on.

$os = Get-WmiObject -Class Win32_OperatingSystem
$version = [Version]$os.Version
if ($version -ge [Version]'6.1' -and $version -lt [Version]'6.2' -and 
$os.ServicePackMajorVersion -lt 1)
{
  # On Windows 7 / Server 2008 R2, Service Pack 1 is required.
  throw 'This package requires Service Pack 1 to be installed first. The 
"KB976932" package may be used to install it.'
}
elseif ($version -ge [Version]'6.0' -and $version -lt [Version]'6.1' -and 
$os.ServicePackMajorVersion -lt 2)
{
  # On Windows Vista / Server 2008, Service Pack 2 is required.
  throw 'This package requires Service Pack 2 to be installed first.'
}
elseif ($version -ge [Version]'5.2' -and $version -lt [Version]'6.0' -and 
$os.ServicePackMajorVersion -lt 2)
{
  # On Windows Server 2003 / XP x64, Service Pack 2 is required.
  throw 'This package requires Service Pack 2 to be installed first.'
}
elseif ($version -ge [Version]'5.1' -and $version -lt [Version]'5.2' -and 
$os.ServicePackMajorVersion -lt 3)
{
  # On Windows XP, Service Pack 3 is required.
  throw 'This package requires Service Pack 3 to be installed first.'
}

An alternative method would be to use the Set-PowerShellExitCode helper method which Chocolatey provides:

https://chocolatey.org/docs/helpers-set-power-shell-exit-code

If you need to specifically set the exit code to something that you use later.

Upvotes: 2

Related Questions