forked from ChrisTitusTech/winutil
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwinget.ps1
More file actions
487 lines (403 loc) · 18.1 KB
/
Copy pathwinget.ps1
File metadata and controls
487 lines (403 loc) · 18.1 KB
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
<#PSScriptInfo
.VERSION 2.0.2
.GUID 3b581edb-5d90-4fa1-ba15-4f2377275463
.AUTHOR asheroto, 1ckov, MisterZeus, ChrisTitusTech
.COMPANYNAME asheroto
.TAGS PowerShell Windows winget win get install installer fix script
.PROJECTURI https://github.com/asheroto/winget-install
.RELEASENOTES
[Version 0.0.1] - Initial Release.
[Version 0.0.2] - Implemented function to get the latest version of winget and its license.
[Version 0.0.3] - Signed file for PSGallery.
[Version 0.0.4] - Changed URI to grab latest release instead of releases and preleases.
[Version 0.0.5] - Updated version number of dependencies.
[Version 1.0.0] - Major refactor code, see release notes for more information.
[Version 1.0.1] - Fixed minor bug where version 2.8 was hardcoded in URL.
[Version 1.0.2] - Hardcoded UI Xaml version 2.8.4 as a failsafe in case the API fails. Added CheckForUpdates, Version, Help functions. Various bug fixes.
[Version 1.0.3] - Added error message to catch block. Fixed bug where appx package was not being installed.
[Version 1.0.4] - MisterZeus optimized code for readability.
[Version 2.0.0] - Major refactor. Reverted to UI.Xaml 2.7.3 for stability. Adjusted script to fix install issues due to winget changes (thank you ChrisTitusTech). Added in all architecture support.
[Version 2.0.1] - Renamed repo and URL references from winget-installer to winget-install. Added extra space after the last line of output.
[Version 2.0.2] - Adjusted CheckForUpdates to include Install-Script instructions and extra spacing.
#>
<#
.SYNOPSIS
Downloads the latest version of winget, its dependencies, and installs everything. PATH variable is adjusted after installation. Reboot required after installation.
.DESCRIPTION
The Install-winget function automates the process of installing the winget package manager. It downloads the latest version of winget and its required dependencies from the source. After downloading, the function installs winget and updates the PATH environment variable to include directories necessary for winget's operation.
This function is designed to be straightforward and easy to use, removing the hassle of manually downloading, installing, and configuring winget. To make the newly installed winget available for use, a system reboot may be required after the execution of this function. This function should be run with administrative privileges.
.EXAMPLE
winget-install
.PARAMETER Version
Displays the version of the script.
.PARAMETER Help
Displays the help information for the script.
.PARAMETER CheckForUpdate
Checks for updates of the script.
.NOTES
Version : 2.0.2
Created by : asheroto
.LINK
Project Site: https://github.com/asheroto/winget-install
#>
[CmdletBinding()]
param (
[switch]$Version,
[switch]$Help,
[switch]$CheckForUpdates
)
# Version
$CurrentVersion = '2.0.2'
$RepoOwner = 'asheroto'
$RepoName = 'winget-install'
# Versions
$ProgressPreference = 'SilentlyContinue' # Suppress progress bar (makes downloading super fast)
# Check if -Version is specified
if ($Version.IsPresent) {
$CurrentVersion
exit 0
}
# Help
if ($Help) {
Get-Help -Name $MyInvocation.MyCommand.Source -Full
exit 0
}
# If user runs "winget-install -Verbose", output their PS and Host info.
if ($PSBoundParameters.ContainsKey('Verbose') -and $PSBoundParameters['Verbose']) {
$PSVersionTable
Get-Host
}
function Get-GitHubRelease {
<#
.SYNOPSIS
Fetches the latest release information of a GitHub repository.
.DESCRIPTION
This function uses the GitHub API to get information about the latest release of a specified repository, including its version and the date it was published.
.PARAMETER Owner
The GitHub username of the repository owner.
.PARAMETER Repo
The name of the repository.
.EXAMPLE
Get-GitHubRelease -Owner "asheroto" -Repo "winget-install"
This command retrieves the latest release version and published datetime of the winget-install repository owned by asheroto.
#>
[CmdletBinding()]
param (
[string]$Owner,
[string]$Repo
)
try {
$url = "https://api.github.com/repos/$Owner/$Repo/releases/latest"
$response = Invoke-RestMethod -Uri $url -ErrorAction Stop
$latestVersion = $response.tag_name
$publishedAt = $response.published_at
# Convert UTC time string to local time
$UtcDateTime = [DateTime]::Parse($publishedAt, [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::RoundtripKind)
$PublishedLocalDateTime = $UtcDateTime.ToLocalTime()
[PSCustomObject]@{
LatestVersion = $latestVersion
PublishedDateTime = $PublishedLocalDateTime
}
} catch {
Write-Error "Unable to check for updates.`nError: $_"
exit 1
}
}
# Generates a section divider for easy reading of the output.
function Write-Section($text) {
<#
.SYNOPSIS
Prints a text block surrounded by a section divider for enhanced output readability.
.DESCRIPTION
This function takes a string input and prints it to the console, surrounded by a section divider made of hash characters. It is designed to enhance the readability of console output.
.PARAMETER text
The text to be printed within the section divider.
.EXAMPLE
Write-Section "Downloading Files..."
This command prints the text "Downloading Files..." surrounded by a section divider.
#>
Write-Output ""
Write-Output ("#" * ($text.Length + 4))
Write-Output "# $text #"
Write-Output ("#" * ($text.Length + 4))
Write-Output ""
}
function Get-NewestLink($match) {
<#
.SYNOPSIS
Retrieves the download URL of the latest release asset that matches a specified pattern from the GitHub repository.
.DESCRIPTION
This function uses the GitHub API to get information about the latest release of the winget-cli repository. It then retrieves the download URL for the release asset that matches a specified pattern.
.PARAMETER match
The pattern to match in the asset names.
.EXAMPLE
Get-NewestLink "msixbundle"
This command retrieves the download URL for the latest release asset with a name that contains "msixbundle".
#>
[CmdletBinding()]
$uri = "https://api.github.com/repos/microsoft/winget-cli/releases/latest"
Write-Verbose "Getting information from $uri"
$get = Invoke-RestMethod -uri $uri -Method Get -ErrorAction stop
Write-Verbose "Getting latest release..."
$data = $get.assets | Where-Object name -Match $match
return $data.browser_download_url
}
function Update-PathEnvironmentVariable {
<#
.SYNOPSIS
Updates the PATH environment variable with a new path for both the User and Machine levels.
.DESCRIPTION
The function will add a new path to the PATH environment variable, making sure it is not a duplicate.
If the new path is already in the PATH variable, the function will skip adding it.
This function operates at both User and Machine levels.
.PARAMETER NewPath
The new directory path to be added to the PATH environment variable.
.EXAMPLE
Update-PathEnvironmentVariable -NewPath "C:\NewDirectory"
This command will add the directory "C:\NewDirectory" to the PATH variable at both the User and Machine levels.
#>
param(
[string]$NewPath
)
foreach ($Level in "Machine", "User") {
# Get the current PATH variable
$path = [Environment]::GetEnvironmentVariable("PATH", $Level)
# Check if the new path is already in the PATH variable
if (!$path.Contains($NewPath)) {
Write-Output "Adding $NewPath to PATH variable for $Level..."
# Add the new path to the PATH variable
$path = ($path + ";" + $NewPath).Split(';') | Select-Object -Unique
$path = $path -join ';'
# Set the new PATH variable
[Environment]::SetEnvironmentVariable("PATH", $path, $Level)
} else {
Write-Output "$NewPath already present in PATH variable for $Level, skipping."
}
}
}
function Handle-Error {
<#
.SYNOPSIS
Handles common errors that may occur during an installation process.
.DESCRIPTION
This function takes an ErrorRecord object and checks for certain known error codes.
Depending on the error code, it writes appropriate warning messages or throws the error.
.PARAMETER ErrorRecord
The ErrorRecord object that represents the error that was caught. This object contains
information about the error, including the exception that was thrown.
.EXAMPLE
try {
# Some code that may throw an error...
} catch {
Handle-Error $_
}
This example shows how you might use the Handle-Error function in a try-catch block.
If an error occurs in the try block, the catch block catches it and calls Handle-Error,
passing the error (represented by the $_ variable) to the function.
#>
param($ErrorRecord)
# Store current value
$OriginalErrorActionPreference = $ErrorActionPreference
# Set to silently continue
$ErrorActionPreference = 'SilentlyContinue'
if ($ErrorRecord.Exception.Message -match '0x80073D06') {
Write-Warning "Higher version already installed."
Write-Warning "That's okay, continuing..."
} elseif ($ErrorRecord.Exception.Message -match '0x80073CF0') {
Write-Warning "Same version already installed."
Write-Warning "That's okay, continuing..."
} elseif ($ErrorRecord.Exception.Message -match '0x80073D02') {
# Stop execution and return the ErrorRecord so that the calling try/catch block throws the error
Write-Warning "Resources modified are in-use. Try closing Windows Terminal / PowerShell / Command Prompt and try again."
Write-Warning "If the problem persists, restart your computer."
return $ErrorRecord
} else {
# For other errors, we should stop the execution and return the ErrorRecord so that the calling try/catch block throws the error
return $ErrorRecord
}
# Reset to original value
$ErrorActionPreference = $OriginalErrorActionPreference
}
# Check for updates
if ($CheckForUpdates) {
$Data = Get-GitHubRelease -Owner $RepoOwner -Repo $RepoName
if ($Data.LatestVersion -gt $CurrentVersion) {
Write-Output "`nA new version of $RepoName is available.`n"
Write-Output "Current version: $CurrentVersion."
Write-Output "Latest version: $($Data.LatestVersion)."
Write-Output "Published at: $($Data.PublishedDateTime).`n"
Write-Output "You can download the latest version from https://github.com/$RepoOwner/$RepoName/releases`n"
Write-Output "Or you can run the following command to update:"
Write-Output "Install-Script winget-install -Force`n"
} else {
Write-Output "`n$RepoName is up to date.`n"
Write-Output "Current version: $CurrentVersion."
Write-Output "Latest version: $($Data.LatestVersion)."
Write-Output "Published at: $($Data.PublishedDateTime)."
Write-Output "`nRepository: https://github.com/$RepoOwner/$RepoName/releases`n"
}
exit 0
}
try {
# Using temp directory for downloads
$tempFolder = [System.IO.Path]::GetTempPath()
# Determine architecture
$cpuArchitecture = (Get-CimInstance -ClassName Win32_Processor).Architecture
# 0 - x86, 9 - x64, 5 - ARM, 12 - ARM64
switch ($cpuArchitecture) {
0 { $arch = "x86" }
9 { $arch = "x64" }
5 { $arch = "arm" }
12 { $arch = "arm64" }
default { throw "Unknown CPU architecture detected." }
}
########################
# VCLibs
########################
# Vars
$vcLibsVersion = "14.00"
$vcLibs = @{
url = "https://aka.ms/Microsoft.VCLibs.$arch.$($vcLibsVersion).Desktop.appx"
}
# Output
Write-Section "Downloading & installing ${arch} VCLibs..."
switch ($cpuArchitecture) {
0 { $arch = "x86" }
9 { $arch = "x64" }
5 { $arch = "arm" }
12 { $arch = "arm64" }
default { throw "Unknown CPU architecture detected." }
}
########################
# VCLibs
########################
# Vars
$vcLibsVersion = "14.00"
$vcLibs = @{
url = "https://aka.ms/Microsoft.VCLibs.$arch.$($vcLibsVersion).Desktop.appx"
}
# Output
Write-Section "Downloading & installing ${arch} VCLibs..."
Write-Output "URL: $($vcLibs.url)"
# Try to install VCLibs
try {
# Add-AppxPackage will throw an error if the app is already installed or higher version installed, so we need to catch it and continue
Add-AppxPackage $vcLibs.url -ErrorAction Stop
} catch {
$errorHandled = Handle-Error $_
if ($null -ne $errorHandled) {
throw $errorHandled
}
$errorHandled = $null
}
########################
# UI.Xaml
########################
# Vars
$uiXamlNupkgVersion = "2.7.3"
$uiXamlAppxFileVersion = "2.7"
$uiXaml = @{
url = "https://www.nuget.org/api/v2/package/Microsoft.UI.Xaml/$uiXamlNupkgVersion"
appxFolder = "tools/AppX/$arch/Release/"
appxFilename = "Microsoft.UI.Xaml.$uiXamlAppxFileVersion.appx"
nupkgFilename = Join-Path -Path $tempFolder -ChildPath "Microsoft.UI.Xaml.$uiXamlNupkgVersion.nupkg"
nupkgFolder = Join-Path -Path $tempFolder -ChildPath "Microsoft.UI.Xaml.$uiXamlNupkgVersion"
}
# Output
Write-Section "Downloading & installing ${arch} UI.Xaml..."
Write-Output "Downloading: $($uiXaml.url)"
Write-Output "Saving as: $($uiXaml.nupkgFilename)"
# Downloads from URL, saves as nupkg
Invoke-WebRequest -Uri $uiXaml.url -OutFile $uiXaml.nupkgFilename
# Extracts the nupkg file
Write-Output "Extracting into: $($uiXaml.nupkgFolder)`n"
Add-Type -Assembly System.IO.Compression.FileSystem
# Extracts the nupkg file
Write-Output "Extracting into: $($uiXaml.nupkgFolder)`n"
Add-Type -Assembly System.IO.Compression.FileSystem
# Check if folder exists and delete if needed
if (Test-Path -Path $uiXaml.nupkgFolder) {
Remove-Item -Path $uiXaml.nupkgFolder -Recurse
}
[IO.Compression.ZipFile]::ExtractToDirectory($uiXaml.nupkgFilename, $uiXaml.nupkgFolder)
# Install XAML
Write-Output "Installing ${arch} XAML..."
$XamlAppxFolder = Join-Path -Path $uiXaml.nupkgFolder -ChildPath $uiXaml.appxFolder
$XamlAppxPath = Join-Path -Path $XamlAppxFolder -ChildPath $uiXaml.appxFilename
Write-Output "Installing Appx Packages in: $XamlAppxFolder"
# For each appx file in the folder, try to install it
Get-ChildItem -Path $XamlAppxPath -Filter *.appx | ForEach-Object {
try {
Write-Output "Installing Appx Package: $($_.Name)"
# Add-AppxPackage will throw an error if the app is already installed
# or a higher version is installed, so we need to catch it and continue
Add-AppxPackage $_.FullName -ErrorAction Stop
} catch {
$errorHandled = Handle-Error $_
if ($null -ne $errorHandled) {
throw $errorHandled
}
$errorHandled = $null
}
}
########################
# winget
########################
# Download winget
Write-Section "Downloading winget..."
Write-Output "Retrieving download URL for winget from GitHub..."
$wingetUrl = Get-NewestLink("msixbundle")
$wingetPath = Join-Path -Path $tempFolder -ChildPath "winget.msixbundle"
$wingetLicenseUrl = Get-NewestLink("License1.xml")
$wingetLicensePath = Join-Path -Path $tempFolder -ChildPath "license1.xml"
Write-Output "`nDownloading: $wingetUrl"
Write-Output "Saving as: $wingetPath"
Invoke-WebRequest -Uri $wingetUrl -OutFile $wingetPath
Write-Output "`nDownloading: $wingetLicenseUrl"
Write-Output "Saving as: $wingetLicensePath"
Invoke-WebRequest -Uri $wingetLicenseUrl -OutFile $wingetLicensePath
# Install winget
Write-Section "Installing winget..."
Write-Output "wingetPath: $wingetPath"
Write-Output "wingetLicensePath: $wingetLicensePath"
# Try to install winget
try {
# Add-AppxPackage will throw an error if the app is already installed or higher version installed, so we need to catch it and continue
Add-AppxPackage -Path $wingetPath -ErrorAction SilentlyContinue
} catch {
$errorHandled = Handle-Error $_
if ($null -ne $errorHandled) {
throw $errorHandled
}
$errorHandled = $null
}
# Add the WindowsApps directory to the PATH variable
Write-Section "Checking and adding WindowsApps directory to PATH variable for current user if not present..."
$WindowsAppsPath = [IO.Path]::Combine([Environment]::GetEnvironmentVariable("LOCALAPPDATA"), "Microsoft", "WindowsApps")
Update-PathEnvironmentVariable -NewPath $WindowsAppsPath
########################
# Cleanup
########################
Write-Section "Cleaning up..."
Remove-Item -Path $uiXaml.nupkgFilename
Remove-Item -Path $uiXaml.nupkgFolder -Recurse
Remove-Item -Path $wingetPath
Remove-Item -Path $wingetLicensePath
########################
# Finished
########################
Write-Section "Installation complete!"
Write-Output "If winget doesn't work right now, you may need to restart your computer.`n"
} catch {
########################
# Error handling
########################
Write-Section "WARNING! An error occurred during installation!"
Write-Warning "Something went wrong. If messages above don't help and the problem persists,"
Write-Warning "Please open an issue at https://github.com/$RepoOwner/$RepoName/issues`n"
# If it's not 0x80073D02 (resources in use), show error
if ($_.Exception.Message -notmatch '0x80073D02') {
Write-Warning "Line number : $($_.InvocationInfo.ScriptLineNumber)"
Write-Warning "Error: $($_.Exception.Message)`n"
}
}