Public/Chocolatey/Install-ChocolateyPackage.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
function Install-ChocolateyPackage
{
    [CmdletBinding(
        DefaultParameterSetName = 'default'
    )]
    param
    (
        # The name of the package to install
        [Parameter(
            Mandatory = $true,
            Position = 0,
            ParameterSetName = 'default',
            ValueFromPipelineByPropertyName = $true
        )]
        [ValidateNotNullOrEmpty()]
        [string]
        $PackageName,

        # The version of the package to install
        [Parameter(
            Mandatory = $false,
            Position = 1,
            ParameterSetName = 'default',
            ValueFromPipelineByPropertyName = $true
        )]
        [ValidateNotNullOrEmpty()]
        [string]
        $PackageVersion = 'any',

        # If passed will upgrade the package to latest if it's already installed
        [Parameter(
            Mandatory = $false
        )]
        [switch]
        $Upgrade,

        # Special param for pipeline usage from things like import-csv
        [Parameter(
            Mandatory = $false,
            ValueFromPipeline = $true,
            ParameterSetName = 'pipeline',
            DontShow
        )]
        [ValidateNotNullOrEmpty()]
        [ChocolateyPackage[]]
        $ChocolateyPackages
    )
    
    begin
    {
        if (!$IsWindows)
        {
            throw "Not a Windows system."
        }
        try
        {
            $ChocoCheck = Get-Command 'choco'
        }
        catch {}
        if (!$ChocoCheck)
        {
            throw "Chocolatey does not appear to be installed or is not available on your path.`nYou can run 'Install-Chocolatey' to install Chocolatey on your system"
        }
        $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
        if (!$currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
        {
            throw "Chocolatey must be run from an elevated PowerShell session."
        }
        $AcceptedVersionStrings = @('any', 'installed', 'present') # A collection of possible package versions strings
        $ValidExitCodes = @(0, 3010, 1641) # 3010 and 1641 are success but restart pending/initiated

        # If we've specified 'upgrade' then grab our list of installed applications and current vs latest versions
        # Doing it this way means we only have to compute it once as opposed to doing it on every single package.
        # It does mean we have to parse Chocolatey's output but that should be fine...
        if ($Upgrade)
        {
            $OutdatedPackages = @()
            try
            {
                $OutdatedArgs = @{
                    FilePath = 'choco'
                    ArgumentList = @('outdated','-r')
                    ExitCodes = $ValidExitCodes
                    PassThru = $true
                    SuppressOut = $true
                }
                if ($VerbosePreference -eq 'Continue')
                {
                    $OutdatedArgs.Remove('SuppressOut')
                }
                Invoke-NativeCommand @OutdatedArgs | Select-Object -ExpandProperty OutputContent |
                    ForEach-Object {
                        # Chocolatey outputs:
                        # package_name|current_version|latest_version|pinned
                        # eg awscli|1.0.0|1.0.1|false
                        # We don't use all this data at present but I've captured it all so that it's there if we need it.
                        $Package = $_.split('|')
                        $OutdatedPackages += [pscustomobject]@{
                            PackageName    = $Package[0]
                            CurrentVersion = $Package[1]
                            LatestVersion  = $Package[2]
                            Pinned         = [System.Convert]::ToBoolean($Package[3])
                        }   
                    }
            }
            catch
            {
                throw "Failed to get a list of upgradable packages.`n$($_.Exception.Message)"
            }
        }
    }
    
    process
    {
        # We cast this to the ChocolateyPackages variable above, as this gets param validation using our ChocolateyPackages class
        # for free! :D
        if (!$ChocolateyPackages)
        {
            $ChocolateyPackages = @{
                Name    = $PackageName
                Version = $PackageVersion
            }
        }
        
        foreach ($ChocolateyPackage in $ChocolateyPackages)
        {
            Write-Verbose "Checking to see if '$($ChocolateyPackage.Name)' is already installed"
            try
            {
                $ListArgs = @{
                    FilePath = 'choco'
                    ArgumentList = @('list', "$($ChocolateyPackage.name)", '-e', '-r', '--local-only')
                    ExitCodes = $ValidExitCodes
                    PassThru = $true
                    SuppressOut = $true
                }
                if ($VerbosePreference -eq 'Continue')
                {
                    $ListArgs.Remove('SuppressOut')
                }
                $testPackage = Invoke-NativeCommand @ListArgs | Select-Object -ExpandProperty OutputContent
            }
            catch
            {
                Write-Error "Failed to determine if '$($ChocolateyPackage.name)' is already installed.`n$($_.Exception.Message)"
                break
            }
            if ($testPackage)
            {
                Write-Verbose "$testPackage is already installed, checking version number"
                # Remove the package name from the output string that Chocolatey gave us,
                # which _should_ just leave us with the version string.
                $CurrentVersion = $testPackage -replace "$($ChocolateyPackage.name)\|", ""
                
                # If we've not requested a specific version of a package then see if we're going to upgrade it
                if ($ChocolateyPackage.version -in $AcceptedVersionStrings)
                {
                    if ($Upgrade)
                    {
                        Write-Verbose "Checking to see if $($ChocolateyPackage.name) can be upgraded"
                        if ($OutdatedPackages.PackageName -contains $ChocolateyPackage.name)
                        {
                            Write-Verbose "Package '$($ChocolateyPackage.name)' is outdated, upgrading"
                            try
                            {
                                $UpgradeArgs = @{
                                    FilePath = 'choco'
                                    ArgumentList = @('upgrade', "$($ChocolateyPackage.name)", '-y')
                                    ExitCodes = $ValidExitCodes
                                    SuppressOut = $true
                                }
                                if ($VerbosePreference -eq 'Continue')
                                {
                                    $UpgradeArgs.Remove('SuppressOut')
                                }
                                Invoke-NativeCommand @UpgradeArgs
                            }
                            catch
                            {
                                Write-Error "Failed to upgrade $($ChocolateyPackage.name).`n$($_.Exception.Message)"
                            }
                        }
                    }
                }
                # If we have requested a specific version of a package then make sure it matches what's currently installed
                else
                {
                    Write-Verbose "Checking installed version of '$($ChocolateyPackage.name)' matches version '$($ChocolateyPackage.version)'"
                    if ($ChocolateyPackage.version -ne $CurrentVersion)
                    {
                        Write-Error "Package '$($ChocolateyPackage.name)' has a mismatched version. Version '$($ChocolateyPackage.version)' was requested but version '$CurrentVersion' is installed"
                    }
                    if ($Upgrade)
                    {
                        Write-Warning "Upgrade parameter will not be honoured for package '$($ChocolateyPackage.name)' as it has a specific version set"
                    }
                }
                
            }
            else
            {
                Write-Verbose "Attempting to install '$($ChocolateyPackage.Name)' version '$($ChocolateyPackage.Version)'"
                $InstallArgs = @("install", "$($ChocolateyPackage.name)", "-y")
                if ($ChocolateyPackage.version -notin $AcceptedVersionStrings)
                {
                    $InstallArgs = $InstallArgs + " --version $($ChocolateyPackage.version)"
                }
                try
                {
                    $InstallArgs = @{
                        FilePath = 'choco'
                        ArgumentList = $InstallArgs
                        ExitCodes = $ValidExitCodes
                        SuppressOut = $true
                    }
                    if ($VerbosePreference -eq 'Continue')
                    {
                        $InstallArgs.Remove('SuppressOut')
                    }
                    Invoke-NativeCommand @InstallArgs
                }
                catch
                {
                    Write-Error "Failed to install package '$($ChocolateyPackage.name)'.`n$($_.Exception.Message)"
                }
            }
        }
    }
    end
    {}
}