Update-PowerShellRelease.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
<#
.SYNOPSIS
    Update PowerShell to the specified version.
#>

function Update-PowerShellRelease {
    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'Default')]
    param (
        [Parameter(ParameterSetName = 'Default')]
        [Switch]$Latest,
        [Parameter(ParameterSetName = 'Default')]
        [ReleaseTypes]$Release = [ReleaseTypes]::Stable,
        [Parameter(ParameterSetName = 'Version')]
        [SemVer]$Version,
        [Parameter(ParameterSetName = 'Default')]
        [Parameter(ParameterSetName = 'Version')]
        [Switch]$Silent,
        [Parameter(ParameterSetName = 'Default')]
        [Parameter(ParameterSetName = 'Version')]
        [hashtable]$InstallOptions,
        [Parameter(ParameterSetName = 'Default')]
        [Parameter(ParameterSetName = 'Version')]
        [Switch]$NotExitConsole,
        [Parameter(ParameterSetName = 'Default')]
        [Parameter(ParameterSetName = 'Version')]
        [string]$Token,
        [Parameter(ParameterSetName = 'Default')]
        [Parameter(ParameterSetName = 'Version')]
        [Switch]$Force
    )
    # This function supports Windows, macOS only
    if (-not ($IsWindows -or $IsMacOS)) {
        Write-Warning $Messages.Update_PowerShellRelease_001
        return
    }

    # Find update version
    $psReleaseInfo = $null
    switch ($PSCmdlet.ParameterSetName) {
        'Version' {  
            $psReleaseInfo = Find-PowerShellRelease -Version $Version -Token $Token
        }
        Default {
            $psReleaseInfo = Find-PowerShellRelease -Latest -Release $Release -Token $Token
        }
    }
    if (-not $psReleaseInfo) {
        Write-Warning $Messages.Update_PowerShellRelease_002
        return
    }
    if ($psReleaseInfo.Version -lt $PSVersionTable.PSVersion -and (-not $Force)) {
        Write-Warning $Messages.Update_PowerShellRelease_003
        return
    }
    if ($psReleaseInfo.Version -eq $PSVersionTable.PSVersion -and (-not $Force)) {
        $releaseName = switch ($Release) {
            'Preview' { $Messages.Update_PowerShellRelease_012 }
            'LTS' { $Messages.Update_PowerShellRelease_013 }
            Default { $Messages.Update_PowerShellRelease_014 }
        }
        Write-Warning ($Messages.Update_PowerShellRelease_004 -f $releaseName)
        return
    }
    WriteInfo ($Messages.Update_PowerShellRelease_005 -f $psReleaseInfo.Version)

    # Download installer asset
    $installerAssetUrls = GetInstallerAssetUrls -Release $psReleaseInfo
    if (@($installerAssetUrls).Count -eq 0) {
        Write-Error $Messages.Update_PowerShellRelease_006
        return
    }
    if (@($installerAssetUrls).Count -gt 1) {
        Write-Warning $Messages.Update_PowerShellRelease_007
        return
    }
    $localInstallerPath = Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath $installerAssetUrls.split("/")[-1]
    if ($PSCmdlet.ShouldProcess('Download PowerShell installer asset')) {
        DownloadFile -Uri $installerAssetUrls -OutFile $localInstallerPath -Token $Token
    } else {
        Write-Warning $Messages.Update_PowerShellRelease_008
        WriteInfo ("(Skip) Download {0}`r`n To {1}..." -f $installerAssetUrls, $localInstallerPath)
    }

    # Do install
    $shouldInstall = $PSCmdlet.ShouldProcess('Install PowerShell')
    WriteInfo ($Messages.Update_PowerShellRelease_009 -f $psReleaseInfo.Version)
    $params = @{
        CustomParameters = @{
            Windows = @{
                NewVersion = $psReleaseInfo.Version
            }
        }
        CommonParameters = [InstallCommonParameters]@{
            InstallerPath  = $localInstallerPath
            InstallOptions = $InstallOptions
            Silent         = $Silent
            ShouldProcess  = $shouldInstall
        }
        
    }
    DoInstall @params

    # Exit PowerShel Console
    if ((-not $NotExitConsole) -or $Silent) {
        WriteInfo $Messages.Update_PowerShellRelease_011
        if ($shouldInstall) {
            Start-Sleep -Seconds 1
            exit 
        } else {
            WriteInfo '(skip) exit console.'
            return 
        }
    }
}

function GetInstallerAssetUrls ([PowerShellCoreRelease]$Release) {
    if ($IsWindows) {
        return GetMSIAssetUrls -Release $Release
    } 
    if ($IsMacOS) {
        return GetPKGAssetUrls -Release $Release
    }
    return
}

function GetMSIAssetUrls ([PowerShellCoreRelease]$Release) {
    if (IsCurrentProcess64bit) {
        return ($Release.Assets | Where-Object { $_.Architecture -eq [AssetArchtectures]::MSI_WIN64 }).DownloadUrl.OriginalString
    }
    return ($Release.Assets | Where-Object { $_.Architecture -eq [AssetArchtectures]::MSI_WIN32 }).DownloadUrl.OriginalString
}

# this function is for unit tests mainly
function GetMacOSProductVersion () {
    try {
        # e.g. macOS Big Sur returns 11.1.
        $major, $minor = (/usr/bin/sw_vers -productVersion).Split('.')
        return ($major, $minor)
    } catch {
        return (0, 0)
    }
}

function GetPKGAssetUrls ([PowerShellCoreRelease]$Release) {
    # On macOS, Package file may be "powershell-[version].*.pkg" or "powershell-lts-[version].*.pkg"
    # So we ignore "powershell-lts-[version].*.pkg".
    $majorVer, $minorVer = GetMacOSProductVersion
    if ($majorVer -ge 11) {
        $asset = if (IsArmCPU) {
            # PKG_OSXARM64
            $Release.Assets | Where-Object { $_.Architecture -eq [AssetArchtectures]::PKG_OSXARM64 }
        } else {
            # PKG_OSX
            $Release.Assets | Where-Object { $_.Architecture -eq [AssetArchtectures]::PKG_OSX -and $_.Name -notlike 'powershell-lts-*.pkg' }
        }
        if ($null -ne $asset) {
            return $asset.DownloadUrl.OriginalString
        }
        return
    }
    if ($majorVer -eq 10) {
        switch ($minorVer) {
            11 {
                # PKG_OSX1011
                # * OSX El Capitan (10.11)
                $asset = $Release.Assets | Where-Object { $_.Architecture -eq [AssetArchtectures]::PKG_OSX1011 }
                if ($null -ne $asset) {
                    return $asset.DownloadUrl.OriginalString
                }
                return
            } 
            { $_ -in (12, 13) } {
                # PKG_OSX1012 or PKG_OSX
                # * macOS Sierra (10.12)
                # * macOS High Sierra (10.13)
                $asset = $Release.Assets | Where-Object { $_.Architecture -eq [AssetArchtectures]::PKG_OSX -and $_.Name -notlike 'powershell-lts-*.pkg' }
                if ($null -ne $asset) {
                    return $asset.DownloadUrl.OriginalString
                }
                $asset = $Release.Assets | Where-Object { $_.Architecture -eq [AssetArchtectures]::PKG_OSX1012 }
                if ($null -ne $asset) {
                    return $asset.DownloadUrl.OriginalString
                }
                return
            }
            Default {
                $asset = if (IsArmCPU) {
                    # PKG_OSXARM64
                    $Release.Assets | Where-Object { $_.Architecture -eq [AssetArchtectures]::PKG_OSXARM64 }
                } else {
                    # PKG_OSX
                    $Release.Assets | Where-Object { $_.Architecture -eq [AssetArchtectures]::PKG_OSX -and $_.Name -notlike 'powershell-lts-*.pkg' }
                }
                if ($null -ne $asset) {
                    return $asset.DownloadUrl.OriginalString
                }
                return
            }
        }
    }
}

class InstallCommonParameters {

    [string]$InstallerPath

    [hashtable]$InstallOptions

    [bool]$Silent

    [bool]$ShouldProcess
}

function DoInstall ([hashtable]$CustomParameters, [InstallCommonParameters]$CommonParameters) {
    if ($IsWindows) {
        InstallMSI -NewVersion $CustomParameters["Windows"]["NewVersion"] -CommonParameters $CommonParameters
        return
    }
    if ($IsMacOS) {
        InstallPKG -CommonParameters $CommonParameters
        return
    }
    return
}

function InstallMSI ([SemVer]$NewVersion, [InstallCommonParameters]$CommonParameters) { 
    $msiArgs = @('/i', '"{0}"' -f $CommonParameters.InstallerPath)
    if ($CommonParameters.Silent) {
        $msiArgs += '/passive'
    }
    # Set the default install options if not specified.
    # Note : These options are valid only for silent installation.
    if ($null -eq $CommonParameters.InstallOptions) {
        if ($NewVersion -ge '6.1.0-preview.2') {
            $CommonParameters.InstallOptions = @{
                ADD_PATH          = 1;
                REGISTER_MANIFEST = 1;
            }
        }
        if ($NewVersion -ge '7.2.0-preview.8') {
            $CommonParameters.InstallOptions["ENABLE_MU"] = 1
            $CommonParameters.InstallOptions["USE_MU"] = 1
        }
    }
    if ($null -ne $CommonParameters.InstallOptions) {
        # Currently following parameters are allowed.
        # INSTALLFOLDER = "C:\PowerShell\" : Install folder
        # ADD_PATH = [0|1] : Add PowerShell to Path Environment Variable
        # REGISTER_MANIFEST = [0|1] : Register Windows Event Logging Manifest
        # ENABLE_PSREMOTING = [0|1] : Enable PowerShell remoting
        # ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL = [0|1] : Add 'Open here' context menus to Explorer
        # ADD_FILE_CONTEXT_MENU_RUNPOWERSHELL = [0|1] : Add 'Run with PowerShell' context menu for PowerShell files
        # ENABLE_MU = [0|1] : Enable updating PowerShell through Microsoft Update or WSUS (recommended)
        # USE_MU = [0|1] : Use Microsoft Update when I check for updates (recommended)
        foreach ($key in $CommonParameters.InstallOptions.Keys) {
            $msiArgs += ('{0}={1}' -f $key, $CommonParameters.InstallOptions[$key])
        }
    }
    if ($CommonParameters.ShouldProcess) {
        WriteInfo ('msiexec.exe {0}' -f ($msiArgs -join ' '))
        Start-Process -FilePath 'msiexec.exe' -ArgumentList $msiArgs
    } else {
        Write-Warning $Messages.Update_PowerShellRelease_010
        WriteInfo ('(skip) msiexec.exe {0}' -f ($msiArgs -join ' '))
    }
}

function InstallPKG ([InstallCommonParameters]$CommonParameters) { 
    # [string]$PkgFile, [bool]$Silent, [hashtable]$InstallOptions, [bool]$ShouldProcess) {
    $targetVolume = '/'
    if ($null -ne $CommonParameters.InstallOptions) {
        # Install volume
        if ($CommonParameters.InstallOptions.ContainsKey('target')) {
            $targetVolume = $CommonParameters.InstallOptions['target']
        }
    }
    if ($CommonParameters.Silent) {
        if ($CommonParameters.ShouldProcess) {
            WriteInfo "/usr/bin/sudo /usr/sbin/installer -pkg ""$($CommonParameters.InstallerPath)"" -target $targetVolume"
            /usr/bin/sudo /usr/sbin/installer -pkg "$($CommonParameters.InstallerPath)" -target $targetVolume
        } else {
            Write-Warning $Messages.Update_PowerShellRelease_010
            WriteInfo "(skip) /usr/bin/sudo /usr/sbin/installer -pkg ""$($CommonParameters.InstallerPath)"" -target $targetVolume"
        }
        return
    }
    if ($CommonParameters.ShouldProcess) {
        WriteInfo "Invoke-Item ""$($CommonParameters.InstallerPath)"""
        Invoke-Item "$($CommonParameters.InstallerPath)"
    } else {
        Write-Warning $Messages.Update_PowerShellRelease_010
        WriteInfo "(skip) Invoke-Item ""$($CommonParameters.InstallerPath)"""
    }
}