-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathWinGet-Update.psm1
747 lines (632 loc) · 26.9 KB
/
WinGet-Update.psm1
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
#Requires -Modules TextTable, TableUI
Set-StrictMode -Version 3
Import-Module "$PSScriptRoot\WinGet-Utils.psm1"
# Used for specifing the default choice when prompting the user.
[int]$DefaultChoiceContinue = 0
[string]$DefaultSource = 'winget'
[string]$CacheFilePath = "$PSScriptRoot/winget.{HOSTNAME}.cache"
<#
.DESCRIPTION
Computes a hash for an array of strings.
#>
function Get-ListHash
{
param (
# The array of strings to hash.
[string[]]$ListData
)
$stringAsStream = [System.IO.MemoryStream]::new()
$writer = [System.IO.StreamWriter]::new($stringAsStream)
$ListData | ForEach-Object { $writer.write($_) }
$writer.Flush()
$stringAsStream.Position = 0
return (Get-FileHash -InputStream $stringAsStream).Hash
}
<#
.DESCRIPTION
Queries "winget upgrade", applies a filter according to ignore-file rule(s)
and resolve output truncation.
.OUTPUTS
An array of objects containing the available upgrades.
#>
function Get-WinGetSoftwareUpgrade
{
param (
# Detruncate any entries in the text-based results by performing additional queries.
[switch]$Detruncate,
# Use the ignore file to filter the available upgrades.
[switch]$NoIgnore,
# Clean the cache prior to fetching upgrades.
[switch]$CleanCache
)
$consoleWidth = [console]::BufferWidth
[console]::BufferWidth = [console]::LargestWindowWidth
$commandArgs = @('upgrade')
if (-not([string]::IsNullOrWhiteSpace($DefaultSource))) {
$commandArgs += @('--source', $DefaultSource)
}
# For better caching, strip any output before the header row of the upgrade table.
$response = winget $commandArgs
$startIndex = ($response | Select-String "^Name " | Select-Object -First 1).LineNumber - 1
$response = $response[$startIndex .. ($response.Length - 1)]
[console]::BufferWidth = $consoleWidth
if ($NoIgnore) {
$ignoredIds = @()
} else {
$ignoredIds = Get-WinGetSoftwareIgnores
}
$cacheHash = Get-ListHash -ListData ($response + $ignoredIds)
$cached = $false
$cacheFile = $CacheFilePath.Replace('{HOSTNAME}', $(hostname).ToLower())
if (Test-Path $cacheFile)
{
if ($CleanCache) {
Remove-Item $cacheFile
} else {
Write-Verbose "Getting upgrade cache ..."
$cache = Get-Content $cacheFile | ConvertFrom-Json
# Compare the hash against the cached hash to determine if the cached upgrade
# data can be used or if the list needs to be reprocessed.
if ($cacheHash -eq $cache.hash)
{
Write-Verbose "Loaded upgrade cache ..."
Write-Verbose "Cached Items: $($cache.upgrades.Count)"
$upgrades = $cache.upgrades
$cached = $true
}
}
}
if (-not($cached)) {
$lastLineRegex = "\d+ upgrades available\."
$splitIndex = ($response | Select-String $lastLineRegex).LineNumber
$upgrades = $response | ConvertFrom-TextTable -LastLineRegEx $lastLineRegex
$lastLineRegex = "\d+ package\(s\)"
if ($splitIndex -le ($response.Count-1)) {
$upgrades += $response[$splitIndex..($response.Count-1)] | ConvertFrom-TextTable -LastLineRegEx $lastLineRegex
}
if (-not($NoIgnore)) {
$upgrades = $upgrades | Where-Object {
if ($_.Id.EndsWith('…')) {
# Determine if it is necessary to resolve a truncated ID,
# to determine if it should be ignored.
$pattern = $_.Id.Replace('…','*').Replace('.','\.')
$patternMatches = @($ignoredIds | Select-String $pattern).Count
if ($patternMatches -ne 0) {
$_ | Resolve-WinGetSoftwareUpgrade
}
}
-not($ignoredIds -contains $_.Id)
}
}
}
if ($Detruncate) {
$upgrades | Resolve-WinGetSoftwareUpgrade
}
$cache = [PSCustomObject]@{
hash = $cacheHash
upgrades = $upgrades
}
$cache | ConvertTo-Json | Set-Content $cacheFile
$upgrades
}
<#
.DESCRIPTION
Resolves truncated upgrade entries. This will modify the existing
PSCustomObject(s).
#>
function Resolve-WinGetSoftwareUpgrade
{
process
{
if ($_.Name -like "*…" -or $_.Id -like "*…") {
Write-Verbose "Resolving $($_.Id) ($($_.Name)) ..."
$commandArgs = @('search', '--id', "$($_.Id.Replace('…',''))")
if (-not([string]::IsNullOrWhiteSpace($DefaultSource))) {
$commandArgs += @('--source', $DefaultSource)
}
$tmp = @(winget $commandArgs | ConvertFrom-TextTable)
if ($tmp.Count -ne 1) {
Write-Warning "Multiple entries for $($_.Id) returned. First entry selected."
}
$_.Id = $tmp[0].Id
$_.Name = $tmp[0].Name
}
}
}
<#
.DESCRIPTION
Attempts to upgrade to the latest version of WinGet-Essentials via the
PSGallery. The various configuration files required by the WinGet-Essentials
cmdlets will be migrated/moved from prior installations, or an error output
will be emitted stating that such a resouce is missing and is needed to
function.
#>
function Update-WinGetEssentials
{
param(
<#
When set, the cmdlet will automatically relaunch using an Administrator
PowerShell instance. This cmdlet requires aministrator privileges
to create Symbolic Links.
#>
[switch]$Administrator,
# Perform all update operations even if no new version was detected.
[switch]$Force
)
if ($Administrator -and -not(Test-Administrator)) {
$boundParamsString = $PSBoundParameters.Keys | ForEach-Object {
if ($PSBoundParameters[$_] -is [switch]) {
if ($PSBoundParameters[$_]) {
"-$($_)"
}
} else {
"-$($_) $($PSBoundParameters[$_])"
}
}
$cmdArgs = "-NoLogo -NoExit -Command Update-WinGetEssentials $($boundParamsString -join ' ')"
Start-Process -Verb RunAs -FilePath 'pwsh' -ArgumentList $cmdArgs
return
}
if (-not(Test-CreateSymlink)) {
$label = 'Microsoft Article'
$url = 'https://learn.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/create-symbolic-links'
Write-Error "The current user does not have the required privileges to create symbolic links. See $(New-HyperLinkText -Label $label -Url $url)."
return
}
Write-Output 'Upgrading module from PSGallery ...'
$current = @(Get-Module WinGet-Essentials -ListAvailable)[0]
Write-Output "- Current Version: $($current.Version)"
Remove-Module -Name WinGet-Essentials
Update-Module -Name WinGet-Essentials
$newest = @(Get-Module WinGet-Essentials -ListAvailable)[0]
Write-Output "- Updated Version: $($newest.Version)"
Import-Module WinGet-Essentials -RequiredVersion $newest.Version
Import-Module (Join-Path -Path (Split-Path $newest.Path -Parent) -ChildPath "modules/WinGet-Utils.psm1")
if (-not($Force) -and ($current.Version -eq $newest.Version)) {
Write-Output "No new version detected."
return
}
Write-Output 'Migrating ignore file (if available) ...'
Initialize-WinGetIgnore
Write-Output 'Migrating "winget.packages.json" (if available) ...'
Initialize-WinGetRestore
Write-Output 'Creating a checkpoint ...'
$jobName = Start-Job -ScriptBlock { Checkpoint-WingetSoftware | Out-Null }
Show-JobProgress $jobName
Write-Output 'Syncing upgrade packages ...'
$jobName = Start-Job -ScriptBlock { Update-WinGetSoftware -Sync | Out-Null }
Show-JobProgress $jobName
Write-Output 'Done.'
}
<#
.DESCRIPTION
Provides an interactive WinGet UI for selectively installing updates.
.EXAMPLE
PS> Update-WingetSoftware
.EXAMPLE
PS> Update-WingetSoftware <WinGetPackageID>[,<AnotherWinGetPackageID>]
.EXAMPLE
PS> Update-WingetSoftware -Sync
#>
function Update-WinGetSoftware
{
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High', PositionalBinding)]
param (
# The ID or list of IDs for software package(s) to update.
[string[]]$Id,
# No upgrade is performed, simply requests latest upgrade info.
[switch]$Sync,
# Interactively install software using install wizard.
[switch]$Interactive,
# Upgrade all software reported as having newer versions available which have
# known installed versions reported.
[switch]$All,
# Include installing software which has no known version installed.
[switch]$UpgradeUnknown,
# Clean the cache
[switch]$CleanCache,
# Indicates to run the command in an Administror PowerShell instance.
[switch]$Administrator,
# Bypasses the ignore file.
[switch]$NoIgnore,
# Bypasses prompts. If a prior upgrade fails, the process will continue
# to the next. NOTE: This overrides -WhatIf and -Confirm; however, it
# does not disable the -Interactive switch.
[switch]$Force,
# Skips syncing latest upgrade info. Ignored if -Sync is specified.
[switch]$NoSync
)
<#
.DESCRIPTION
Check the result of the last shell command. On error, increment an error counter
and then prompt the user if execution of the script should continue.
.OUTPUTS
True if last command was successful; otherwise false.
#>
function Test-LastCommandResult
{
param(
# The current error count, on error, this value will be incremented.
[ref]$ErrorCount
)
$result = $LASTEXITCODE -eq 0
if (-not($result)) {
$ErrorCount.Value++
}
return $result
}
<#
.DESCRIPTION
Reports to the user that an error occurred and prompts the user if the script
should continue. If the user answers 'No' the script will exit immediately.
#>
function Request-ContinueOnError
{
param(
# The error code.
[int]$Code,
# The current error count.
[int]$ErrorCount,
# The force state as specified by the user. When set, it will bypass,
# prompts and continue on with execution.
[switch]$Force,
# The decision (index) made by the user.
[ref]$Action,
# Command details that will be output to warning log.
[string]$CmdDetails
)
Write-Output ""
$url = "https://github.com/microsoft/winget-cli/blob/master/doc/windows/package-manager/winget/returnCodes.md"
$label = "More Info"
if ([string]::IsNullOrWhiteSpace($CmdDetails)) {
Write-Warning "An error (code: $("0x{0:X08}" -f $Code)) occurred while executing the last step."
} else {
Write-Warning "An error (code: $("0x{0:X08}" -f $Code)) occurred while executing:"
Write-Warning $CmdDetails
}
Write-Warning "Additional details here: $(New-HyperLinkText -Url $url -Label $label)"
if ($Force) {
return
}
$abortIndex = 2
$title = $null # not used
$question = "What action should be performed?"
$choices = @(
[System.Management.Automation.Host.ChoiceDescription]::new("&Continue", "Continue installing other software (if available).")
[System.Management.Automation.Host.ChoiceDescription]::new("&Retry", "Retry installation of the current software package.")
[System.Management.Automation.Host.ChoiceDescription]::new("&Abort", "Stop and exit installation process.")
)
$Action.Value = $Host.UI.PromptForChoice($title, $question, $choices, $DefaultChoiceContinue)
if ($Action.Value -eq $abortIndex) {
throw "Aborted (Errors = $ErrorCount)."
}
Write-Output ""
}
<#
.DESCRIPTION
Get the caches item for the specified package identifier.
#>
function Get-ItemFromCache
{
param(
# Package Identifier to get the cache entry.
[string]$Id
)
$cacheFile = $CacheFilePath.Replace('{HOSTNAME}', $(hostname).ToLower())
if (-not(Test-Path $cacheFile)) {
return $null
}
$cache = Get-Content $cacheFile | ConvertFrom-Json
$cachedItem = $cache.upgrades | Where-Object {
$_.Id -eq $Id
}
return $cachedItem
}
<#
.DESCRIPTION
Removes and item from the upgrade cache.
#>
function Remove-UpgradeItemFromCache
{
param (
# The upgrade item to remove from cache.
[PSCustomObject]$Item
)
$cacheFile = $CacheFilePath.Replace('{HOSTNAME}', $(hostname).ToLower())
if (-not(Test-Path $cacheFile)) {
return
}
$cache = Get-Content $cacheFile | ConvertFrom-Json
$upgrades = $cache.upgrades | Where-Object {
$_.Id -ne $Item.Id
}
# Note: currently the hash depends only on the ignore file and winget's
# raw response data for the upgrade list, so there is no need to
# recompute the hash for this operation. However, because there are
# several complications with detecting whether an update completed
# successfully, it makes sense to simply invalidate the hash to
# force a refresh after the user updated packages.
$cache = [PSCustomObject]@{
hash = "0"
upgrades = $upgrades
}
$cache | ConvertTo-Json | Set-Content $cacheFile
}
<#
.DESCRIPTION
Returns the arguments to be used for performing an update via WinGet.
#>
function Get-WinGetSoftwareUpgradeArgs
{
param (
# The item containing the package to update along with its metadata.
[PSCustomObject]$Item,
# Provide user-interactive installation for the specified package.
[switch]$Interactive
)
$commandArgs = @('upgrade', '--id', $Item.Id, '--version', $Item.Available)
if (-not([string]::IsNullOrWhiteSpace($DefaultSource))) {
$commandArgs += @('--source', $DefaultSource)
}
if ($Interactive) {
$commandArgs += '--interactive'
}
return $commandArgs
}
<#
.DESCRIPTION
Updates the specified package.
#>
function Update-Software
{
param (
# The item containing the package to update along with its metadata.
[PSCustomObject]$Item,
# Provide user-interactive installation for the specified package.
[switch]$Interactive,
# Set true when software installed successfully (note, some packages
# will not report success for various reasons even when the
# software did not encounter an error during the update. One example
# of this is when a package requires a reboot to complete.
[ref]$Success,
# The error count, tracks the number of errors encountered through
# the update process.
[ref]$ErrorCount,
# The force state as specified by the user. When set, it will bypass,
# prompts and continue on with execution.
[switch]$Force
)
# From https://github.com/microsoft/winget-cli/blob/master/src/AppInstallerSharedLib/Public/AppInstallerErrors.h
$UPDATE_NOT_APPLICABLE = 0x8A15002B
$done = $false
while (-not($done)) {
Write-Verbose "Updating '$($Item.Id)' ..."
$commandArgs = Get-WinGetSoftwareUpgradeArgs -Item $Item -Interactive:$Interactive
winget $commandArgs
$upgradeOk = $LASTEXITCODE -eq 0
if (-not($upgradeOk) -and ($LASTEXITCODE -eq $UPDATE_NOT_APPLICABLE)) {
# This is a best-effort workaround for an issue currently present in
# winget where the listing reports an update, but it is not possible
# to 'upgrade'. Instead, use the 'install' command. This is
# typically due to a different installer used for the current
# installation versus what is available on the winget source. In
# this case, try with --uninstall-previous, but support for this is
# not guaranteed. If this fails, the user likely needs to
# "winget uninstall" and then "winget install". This could
# potentially be handled here, but there may be issues with ensuring
# the install state is maintained. For now it is best to force the
# user to upgrade this package manually.
$commandArgs[0] = 'install'
$commandArgs += '--uninstall-previous'
Write-Verbose "command: winget $commandArgs"
winget $commandArgs
}
# TODO: Ignore exit code 3010 (seems to indicate "restart required")?
if (Test-LastCommandResult -ErrorCount $ErrorCount -Force:$Force) {
$done = $true
Write-Verbose "Updated '$($Item.Id)'"
Write-Verbose "`tOld Version: [$($Item.Version)]"
Write-Verbose "`tNew Version: [$($Item.Available)]"
Write-Output ""
$Success.Value = $true
} else {
$action = 0
Request-ContinueOnError -Code $LastExitCode -ErrorCount $ErrorCount.Value -Force:$Force -Action ([ref]$action) -CmdArgs @('winget', $commandArgs)
$done = $action -eq $DefaultChoiceContinue # The 'Abort' action is handled by Request-ContinueOnError
$Success.Value = $false
}
}
}
<#
.DESCRIPTION
Renders output to convey progress.
#>
function Write-ProgressHelper
{
param (
[PSObject]$UpgradeTable,
[int]$UpgradeIndex
)
$i = $UpgradeIndex + 1
$bar = ('─' * $Host.UI.RawUI.WindowSize.Width) # Match current console width
Write-Output "`n$bar"
Write-Output "[ $i / $($UpgradeTable.Count) ] Upgrading '$($UpgradeTable[$UpgradeIndex].Name)'"
Write-Output "$bar`n"
}
[int]$errorCount = 0
if ($Administrator -and -not(Test-Administrator)) {
$boundParamsString = $PSBoundParameters.Keys | ForEach-Object {
if ($PSBoundParameters[$_] -is [switch]) {
if ($PSBoundParameters[$_]) {
"-$($_)"
}
} else {
"-$($_) $($PSBoundParameters[$_] -join ',')"
}
}
$cmdArgs = "-NoLogo -NoExit -Command Update-WingetSoftware $($boundParamsString -join ' ')"
Start-Process -Verb RunAs -FilePath "pwsh" -ArgumentList $cmdArgs
return
}
$cacheFile = $CacheFilePath.Replace('{HOSTNAME}', $(hostname).ToLower())
if (-not([string]::IsNullOrWhiteSpace($Id))) {
$upgradeTable = @()
$Id | ForEach-Object {
$upgradeItem = Get-ItemFromCache -Id $_
if ($null -eq $upgradeItem) {
Write-Warning "`"$_`" was not found in cache and will not be upgraded."
} else {
$upgradeTable += $upgradeItem
}
}
$ConfirmPreference = 'None'
$upgradeIndex = 0
$upgradeTable | ForEach-Object {
Write-ProgressHelper -UpgradeTable $upgradeTable -UpgradeIndex $upgradeIndex
$upgradeIndex++
Write-Verbose "command: winget $(Get-WinGetSoftwareUpgradeArgs -Item $_ -Interactive:$Interactive)"
if ($Force -or $PSCmdlet.ShouldProcess($_.Id)) {
$upgraded = $false
Update-Software -Item $_ -Interactive:$Interactive -Success ([ref]$upgraded) -ErrorCount ([ref]$errorCount) -Force:$Force
if ($upgraded) {
Remove-UpgradeItemFromCache -Item $_
}
}
}
return
}
Write-Output "Getting winget upgrades ..."
$upgradeTable = @()
$cacheFile = $CacheFilePath.Replace('{HOSTNAME}', $(hostname).ToLower())
if ($Sync) {
$jobName = Start-Job -ScriptBlock {
$commandArgs = @('source', 'update')
if (-not([string]::IsNullOrWhiteSpace($DefaultSource))) {
$commandArgs += @('--name', $DefaultSource)
}
winget $commandArgs
Get-WinGetSoftwareUpgrade -UseIgnores -Detruncate
}
Show-JobProgress $jobName
$upgradeTable = (Get-Content $cacheFile | ConvertFrom-Json).upgrades
if ($upgradeTable.Count -gt 0) {
Write-Output "Available Upgrades:"
$upgradeTable | Format-Table
}
return
}
if ($NoSync) {
Write-Output "Sync Skipped."
} else {
$jobName = Start-Job -ScriptBlock {
Get-WinGetSoftwareUpgrade -UseIgnores -Detruncate
}
Show-JobProgress $jobName
}
if (Test-Path $cacheFile) {
$upgradeTable = (Get-Content $cacheFile | ConvertFrom-Json).upgrades
}
if ($upgradeTable.Count -eq 0) {
Write-Output "No packages to be updated ..."
$selections =@()
# Do nothing
} elseif ($All) {
# Upgrade all packages
$selections = $upgradeTable | ForEach-Object { $true }
$upgradeTable = $upgradeTable | Sort-Object -Property Name
} else {
# Ask user to select packages to install
$upgradeTable = $upgradeTable | Sort-Object -Property Name
$selections = $upgradeTable | ForEach-Object { $false }
$showPackageDetailsScriptBlock = {
param($currentSelections, $selectedIndex)
$commandArgs = @('show', $upgradeTable[$selectedIndex].Id)
if (-not([string]::IsNullOrWhiteSpace($DefaultSource))) {
$commandArgs += @('--source', $DefaultSource)
}
$consoleEncoding = [console]::OutputEncoding
[console]::OutputEncoding = [System.Text.UTF8Encoding]::new()
$details = winget $commandArgs --no-vt
[console]::OutputEncoding = $consoleEncoding
$firstLine = $details | Select-String -Pattern 'Found\s+(.*\[.*\])'
if ($firstLine.Matches.Count -eq 1) {
$details = $details[$firstLine.LineNumber..($details.Length - 1)]
Show-Paginated -TextData $details -Title $firstLine.Matches[0].Groups[1].Value
Hide-TerminalCursor
}
}
$TableUIArgs = @{
Table = $upgradeTable
Selections = ([ref]$selections)
Title = 'Select Software to Update'
DefaultMemberToShow = @('Name','Available','Version')
SelectedItemMembersToShow = @('Name','Id','Version','Available')
EnterKeyDescription = 'Press ENTER to show selection details.'
EnterKeyScript = $showPackageDetailsScriptBlock
}
Enter-AltScreenBuffer
Hide-TerminalCursor
Show-TableUI @TableUIArgs
Exit-AltScreenBuffer
}
Write-Output "Upgrades available: $($upgradeTable.Count)"
if ($null -eq $selections) {
$upgradeTable = @()
} else {
$upgradeTable = @($upgradeTable | Where-Object { $selections[$upgradeTable.indexOf($_)] })
}
Write-Output "Upgrades selected: $($upgradeTable.Count)"
if ($upgradeTable.Count -ne 0) {
$upgradeIndex = 0
$upgradeTable | ForEach-Object { Write-Output "- $($_.Id) ($($_.Name))" }
foreach ($upgradeItem in $upgradeTable) {
Write-ProgressHelper -UpgradeTable $upgradeTable -UpgradeIndex $upgradeIndex
if (($upgradeItem.Version -eq 'Unknown') -and -not($UpgradeUnknown)) {
Write-Warning "'$($upgradeItem.Id)': Unknown version installed. Install manually or specify '-UpgradeUnknown' to bypass this check."
continue
}
Write-Verbose "command: winget $(Get-WinGetSoftwareUpgradeArgs -Item $upgradeItem -Interactive:$Interactive)"
if ($Force -or $PSCmdlet.ShouldProcess($upgradeItem.Id)) {
$upgraded = $false
Update-Software $upgradeItem -Interactive:$Interactive -Success ([ref]$upgraded) -ErrorCount ([ref]$errorCount) -Force:$Force
if ($upgraded) {
Remove-UpgradeItemFromCache -Item $upgradeItem
}
}
$upgradeIndex++
}
}
if ($errorCount -gt 0) {
Write-Error "Done (Errors = $errorCount)."
} else {
Write-Output 'Done.'
}
}
$UpgradesScriptBlock = {
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
$cacheFile = $CacheFilePath.Replace('{HOSTNAME}', $(hostname).ToLower())
if (Test-Path $cacheFile) {
$upgrades = (Get-Content $cacheFile | ConvertFrom-Json).upgrades
if ($null -ne $upgrades) {
$commandLine = $commandAst.Extent.Text | Select-String -Pattern "\s+\-$parameterName\s+"
if (($null -ne $commandLine) -and ($commandLine.Matches.Count -gt 0)) {
$commandLine = $commandAst.Extent.Text.Split(($commandLine.Matches | Select-Object -Last 1).Value) | Select-Object -Last 1
} else {
$commandLine = $commandAst.Extent.Text.Split(" ") | Select-Object -Skip 1
}
# Extract the values that have been entered so far
if ($null -ne $commandLine) {
$enteredUpgrades = $commandLine.Split(",") | ForEach-Object { $_.Trim('"').Trim("'") }
} else {
$enteredUpgrades = @()
}
# Filter out the values that have already been entered
$completionUpgrades = $upgrades | Where-Object { $_.Id -notin $enteredUpgrades }
$completionUpgrades | Where-Object { $_.Id -like "$wordToComplete*" } | ForEach-Object {
$toolTip = "$($_.Name) [$($_.Version) --> $($_.Available)]"
[System.Management.Automation.CompletionResult]::new($_.Id, $_.Id, 'ParameterValue', $toolTip)
}
}
}
}
Register-ArgumentCompleter -CommandName Update-WinGetSoftware -ParameterName Id -ScriptBlock $UpgradesScriptBlock