-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwinget-installscript.ps1
More file actions
518 lines (428 loc) · 18.3 KB
/
winget-installscript.ps1
File metadata and controls
518 lines (428 loc) · 18.3 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
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
[CmdletBinding()]
param(
[switch] $SetupWinget,
[switch] $UpgradeAll,
[Parameter(Position = 0, ValueFromRemainingArguments = $true)]
[string[]] $Apps
)
# =====================================================================
# Global Settings – Speed & Network
# =====================================================================
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
$PSDefaultParameterValues['Invoke-WebRequest:UseBasicParsing'] = $true
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# =====================================================================
# GitHub: aktuellstes WinGet-Release (Bundle + Dependencies.zip)
# =====================================================================
function Get-WingetLatestReleaseAssets {
[CmdletBinding()]
param()
$releasesUrl = 'https://api.github.com/repos/microsoft/winget-cli/releases/latest'
Write-Host "INFO - Querying latest WinGet release from GitHub..."
$release = Invoke-RestMethod -Uri $releasesUrl
$bundleAsset = $release.assets |
Where-Object { $_.browser_download_url.EndsWith('msixbundle') } |
Select-Object -First 1
$depsAsset = $release.assets |
Where-Object { $_.name -eq 'DesktopAppInstaller_Dependencies.zip' } |
Select-Object -First 1
if (-not $bundleAsset) {
throw "No MSIX bundle found in latest winget release."
}
if (-not $depsAsset) {
throw "No DesktopAppInstaller_Dependencies.zip found in latest winget release."
}
Write-Host "INFO - Latest WinGet tag: $($release.tag_name)"
Write-Host "INFO - Bundle: $($bundleAsset.name)"
Write-Host "INFO - Deps : $($depsAsset.name)"
return [pscustomobject]@{
BundleUrl = $bundleAsset.browser_download_url
DepsUrl = $depsAsset.browser_download_url
Tag = $release.tag_name
}
}
# =====================================================================
# Dependencies aus DesktopAppInstaller_Dependencies.zip installieren
# (VCLibs + UWPDesktop + WindowsAppRuntime 1.8)
# =====================================================================
function Install-WingetDependencies {
Write-Host "INFO - Installing WinGet dependencies (VCLibs + UWPDesktop + WindowsAppRuntime)..."
$assets = Get-WingetLatestReleaseAssets
$tempRoot = Join-Path $env:TEMP "WingetSetup-Dependencies"
if (Test-Path $tempRoot) {
Remove-Item $tempRoot -Recurse -Force -ErrorAction SilentlyContinue | Out-Null
}
New-Item $tempRoot -ItemType Directory -Force | Out-Null
$zipPath = Join-Path $tempRoot "DesktopAppInstaller_Dependencies.zip"
$depsRoot = Join-Path $tempRoot "deps"
try {
Write-Host "INFO - Downloading dependencies zip..."
Invoke-WebRequest -Uri $assets.DepsUrl -OutFile $zipPath
if (-not (Test-Path $zipPath)) {
throw "Dependencies zip was not downloaded correctly."
}
Expand-Archive -Path $zipPath -DestinationPath $depsRoot -Force
$x64Dir = Join-Path $depsRoot "x64"
if (-not (Test-Path $x64Dir)) {
throw "x64 directory not found in dependencies zip."
}
$appxFiles = Get-ChildItem -Path $x64Dir -Filter '*.appx' | Sort-Object Name
foreach ($file in $appxFiles) {
Write-Host "INFO - Installing dependency: $($file.Name)"
$maxAttempts = 4
$delaySeconds = 20
for ($i = 1; $i -le $maxAttempts; $i++) {
try {
Add-AppxPackage -Path $file.FullName -ErrorAction Stop
Write-Host "OK - Dependency installed/updated: $($file.Name)"
break
}
catch {
$hr = $_.Exception.HResult
$hex = '0x{0:X8}' -f ($hr -band 0xffffffff)
$text = $_ | Out-String
# 0x80073D06 -> höhere Version bereits installiert (OK, überspringen)
if ($hex -eq '0x80073D06') {
Write-Host "INFO - Skipping $($file.Name): newer version already installed (HResult ${hex})."
break
}
# 0x80073D02 / 0x80073D0A -> Ressourcen in Benutzung / Installation läuft (Retry)
if (($hex -eq '0x80073D02' -or $hex -eq '0x80073D0A') -and $i -lt $maxAttempts) {
Write-Host "WARN - Dependency blocked (HResult ${hex}) – Windows components are in use." -ForegroundColor Yellow
try {
Write-Host "INFO - Retrying with -ForceApplicationShutdown..."
Add-AppxPackage -Path $file.FullName -ForceApplicationShutdown -ErrorAction Stop
Write-Host "OK - Dependency installed/updated with ForceApplicationShutdown: $($file.Name)"
break
}
catch {
Write-Host "INFO - Waiting ${delaySeconds}s before retry ($i/$maxAttempts)..."
Start-Sleep -Seconds $delaySeconds
continue
}
}
# Wenn nach den Retries immer noch blockiert -> klarer Hinweis
if ($hex -eq '0x80073D02' -or $hex -eq '0x80073D0A') {
Write-Host ""
Write-Host "ERROR - Dependency installation is blocked by running Windows apps/components." -ForegroundColor Red
Write-Host "INFO - Please close Widgets / Notepad / WebExperience (Client.WebExperience) or log off once, then retry." -ForegroundColor Red
Write-Host $text
throw
}
Write-Host "WARN - Failed to install dependency $($file.Name) (HResult ${hex}):"
Write-Host $text
throw
}
}
}
Write-Host "OK - All dependencies from dependencies zip processed."
}
finally {
Remove-Item $tempRoot -Recurse -Force -ErrorAction SilentlyContinue | Out-Null
}
}
# =====================================================================
# WinGet / DesktopAppInstaller installieren oder aktualisieren
# =====================================================================
function Install-WingetCli {
Write-Host "INFO - Checking WinGet / DesktopAppInstaller..."
$pkgFamily = 'Microsoft.DesktopAppInstaller_8wekyb3d8bbwe'
$minWingetVersion = [version]"1.12.400.0"
# 1) Aktuelle WinGet-Version prüfen
$needInstall = $true
try {
$raw = winget --version 2>&1
if ($LASTEXITCODE -eq 0 -and $raw) {
$verString = ($raw | Select-Object -First 1).Trim().TrimStart('v','V')
$ver = [version]$verString
Write-Host "INFO - Current WinGet version: $ver"
if ($ver -ge $minWingetVersion) {
Write-Host "OK - WinGet is already up to date (>= $minWingetVersion)."
$needInstall = $false
}
else {
Write-Host "WARN - WinGet is too old (v$ver < $minWingetVersion) – updating..."
}
}
else {
Write-Host "INFO - WinGet not callable (exitcode $LASTEXITCODE) – will install."
}
}
catch {
Write-Host "WARN - Error while checking WinGet version – will install:"
Write-Host ($_ | Out-String)
}
if (-not $needInstall) { return }
# kleine Helper-Funktion für die Bundle-Installation mit Retry
function Invoke-DesktopAppInstallerBundle {
param(
[string]$BundlePath,
[int]$MaxAttempts = 5,
[int]$DelaySeconds = 20
)
for ($i = 1; $i -le $MaxAttempts; $i++) {
Write-Host "INFO - Installing DesktopAppInstaller/WinGet bundle (try $i/$MaxAttempts)..."
try {
Add-AppxPackage -Path $BundlePath -ErrorAction Stop
Write-Host "OK - DesktopAppInstaller bundle installed."
return
}
catch {
$hr = $_.Exception.HResult
$hex = ('0x{0:X8}' -f ($hr -band 0xffffffff))
Write-Host "WARN - Bundle installation failed with HResult ${hex}:"
Write-Host ($_ | Out-String)
# typische Deployment-Fehler, wenn der Store/AppInstaller gerade in Benutzung ist:
# 0x80073D02 / RESOURCES_IN_USE
# 0x80073D0A / INSTALL_IN_PROGRESS
if (($hex -eq '0x80073D02' -or $hex -eq '0x80073D0A') -and $i -lt $MaxAttempts) {
Write-Host "INFO - Deployment in use / ongoing. Retrying with -ForceApplicationShutdown..."
try {
Add-AppxPackage -Path $BundlePath -ForceApplicationShutdown -ErrorAction Stop
Write-Host "OK - DesktopAppInstaller bundle installed with ForceApplicationShutdown."
return
}
catch {
Write-Host "INFO - Waiting $DelaySeconds seconds before next retry..."
Start-Sleep -Seconds $DelaySeconds
continue
}
}
throw # andere Fehler oder letzter Versuch -> nach außen geben
}
}
throw "DesktopAppInstaller bundle installation failed after $MaxAttempts attempts."
}
# 2) Bundle herunterladen und lokal installieren
$assets = Get-WingetLatestReleaseAssets
$tempRoot = Join-Path $env:TEMP "WingetSetup-Bundle"
if (Test-Path $tempRoot) {
Remove-Item $tempRoot -Recurse -Force -ErrorAction SilentlyContinue | Out-Null
}
New-Item $tempRoot -ItemType Directory -Force | Out-Null
$bundlePath = Join-Path $tempRoot "DesktopAppInstaller_latest.msixbundle"
try {
Write-Host "INFO - Downloading DesktopAppInstaller bundle..."
Invoke-WebRequest -Uri $assets.BundleUrl -OutFile $bundlePath
if (-not (Test-Path $bundlePath)) {
throw "Bundle msixbundle was not downloaded correctly."
}
# >>> hier statt direktem Add-AppxPackage den Retry-Wrapper verwenden
Invoke-DesktopAppInstallerBundle -BundlePath $bundlePath -MaxAttempts 5 -DelaySeconds 20
# nach der Bundle-Installation WinGet/Store-App für den Benutzer registrieren (falls nötig)
try {
Add-AppxPackage -RegisterByFamilyName -MainPackage $pkgFamily -ErrorAction Stop
Write-Host "OK - WinGet registration requested after bundle installation."
}
catch {
Write-Host "WARN - Failed to register WinGet after bundle installation:"
Write-Host ($_ | Out-String)
}
}
finally {
Remove-Item $tempRoot -Recurse -Force -ErrorAction SilentlyContinue | Out-Null
}
# 3) Version nach Installation nochmal prüfen
try {
Start-Sleep -Seconds 3
$raw2 = winget --version 2>&1
if ($LASTEXITCODE -eq 0 -and $raw2) {
$verString2 = ($raw2 | Select-Object -First 1).Trim().TrimStart('v','V')
$ver2 = [version]$verString2
Write-Host "OK - WinGet CLI now reports: $ver2"
if ($ver2 -lt $minWingetVersion) {
Write-Host "WARN - WinGet version after install still below required $minWingetVersion."
}
}
else {
Write-Host "WARN - WinGet still not callable after install (exitcode $LASTEXITCODE)."
}
}
catch {
Write-Host "WARN - Error while checking WinGet version after install:"
Write-Host ($_ | Out-String)
}
}
# =====================================================================
# Apps via winget installieren (für -Apps ...)
# =====================================================================
function Invoke-WingetInstallForApps {
param(
[Parameter(Mandatory = $true)]
[string[]] $AppIds
)
$wingetCmd = Get-Command winget -ErrorAction SilentlyContinue
if (-not $wingetCmd) {
Write-Host "ERROR - winget command not found. Please run with -SetupWinget first."
exit 1
}
$failedApps = @()
$overallFailed = 0
$total = $AppIds.Count
$index = 0
foreach ($id in $AppIds) {
if ([string]::IsNullOrWhiteSpace($id)) { continue }
$index++
Write-Host "INFO - [$index/$total] Installing app via winget: $id"
$args = @(
"install",
"--id", $id,
"--accept-source-agreements",
"--accept-package-agreements",
"--silent",
"--disable-interactivity"
)
$proc = Start-Process -FilePath $wingetCmd.Source -ArgumentList $args -NoNewWindow -PassThru -Wait
if ($proc.ExitCode -eq 0) {
Write-Host "OK - App installed successfully: $id"
}
else {
Write-Host "ERROR - App installation failed for '$id' with exit code $($proc.ExitCode). Skipping and continuing..."
$overallFailed++
$failedApps += $id
}
}
if ($overallFailed -gt 0) {
$list = $failedApps -join ", "
Write-Host "FAILED_APPS: $list"
exit 1
}
else {
Write-Host "OK - All selected apps installed successfully."
exit 0
}
}
# =====================================================================
# Upgradable Apps aus 'winget upgrade' einlesen
# =====================================================================
function Get-WingetUpgradableApps {
$wingetCmd = Get-Command winget -ErrorAction SilentlyContinue
if (-not $wingetCmd) {
Write-Host "ERROR - winget command not found. Please run with -SetupWinget first."
return @()
}
# Winget-Ausgabe holen
$raw = & $wingetCmd.Source upgrade --include-unknown --accept-source-agreements 2>&1
$items = @()
$inTable = $false
foreach ($line in $raw) {
if (-not $inTable) {
# Header erkennen (Name Id Version Available Source)
if ($line -match '^\s*Name\s+Id\s+Version') {
$inTable = $true
}
continue
}
if ([string]::IsNullOrWhiteSpace($line)) { continue }
if ($line -match '^-{3,}') { continue }
# Per „zwei oder mehr Spaces“ in Spalten aufsplitten
$parts = $line -split '\s{2,}'
if ($parts.Length -lt 3) { continue }
# Headerzeile überspringen (falls mehrmals)
if ($parts[0].Trim() -eq 'Name' -and $parts[1].Trim() -eq 'Id') { continue }
$name = $parts[0].Trim()
$id = $parts[1].Trim()
$current = $parts[2].Trim()
$available = if ($parts.Length -ge 4) { $parts[3].Trim() } else { "" }
if ($id) {
$items += [pscustomobject]@{
Name = $name
Id = $id
Current = $current
Available = $available
}
}
}
return $items
}
# =====================================================================
# Alle von winget verwaltbaren Programme aktualisieren + Summary
# =====================================================================
function Invoke-WingetUpgradeAll {
$wingetCmd = Get-Command winget -ErrorAction SilentlyContinue
if (-not $wingetCmd) {
Write-Host "ERROR - winget command not found. Please run with -SetupWinget first."
exit 1
}
# 1) Vorher schauen, was überhaupt upgradebar ist
$before = Get-WingetUpgradableApps
if ($before.Count -eq 0) {
Write-Host "INFO - No upgradable packages found."
Write-Host "UPGRADE_SUMMARY_BEGIN"
Write-Host "UPGRADE_NONE"
Write-Host "UPGRADE_SUMMARY_END"
exit 0
}
Write-Host "INFO - Found $($before.Count) upgradable package(s)."
foreach ($pkg in $before) {
Write-Host ("PENDING - {0} ({1}) {2} -> {3}" -f $pkg.Name, $pkg.Id, $pkg.Current, $pkg.Available)
}
Write-Host ""
Write-Host "INFO - Running 'winget upgrade --all' ..."
Write-Host "INFO - Hinweis: Es werden nur Programme aktualisiert,"
Write-Host " die über winget verwaltet werden können."
# 2) Upgrade durchführen
$args = @(
"upgrade",
"--all",
"--accept-source-agreements",
"--accept-package-agreements"
)
$proc = Start-Process -FilePath $wingetCmd.Source `
-ArgumentList $args `
-NoNewWindow `
-PassThru `
-Wait
$exitCode = $proc.ExitCode
# 3) Nachher erneut schauen, was noch upgradebar ist
$after = Get-WingetUpgradableApps
$afterIds = $after | ForEach-Object { $_.Id }
$updated = @()
$remaining = @()
foreach ($pkg in $before) {
if ($afterIds -contains $pkg.Id) {
$remaining += $pkg
}
else {
$updated += $pkg
}
}
Write-Host ""
Write-Host "UPGRADE_SUMMARY_BEGIN"
foreach ($pkg in $updated) {
Write-Host ("UPDATED_APP: {0} | {1} | {2} -> {3}" -f $pkg.Name, $pkg.Id, $pkg.Current, $pkg.Available)
}
foreach ($pkg in $remaining) {
Write-Host ("NOT_UPDATED_APP: {0} | {1} | {2} -> {3}" -f $pkg.Name, $pkg.Id, $pkg.Current, $pkg.Available)
}
Write-Host "UPGRADE_SUMMARY_END"
if ($exitCode -eq 0) {
Write-Host "OK - winget upgrade --all completed with exit code 0."
}
else {
Write-Host "WARN - winget upgrade --all finished with exit code $exitCode"
}
exit $exitCode
}
# =====================================================================
# Main
# =====================================================================
if ($SetupWinget.IsPresent) {
Write-Host "INFO - Running in SetupWinget mode."
Install-WingetDependencies
Install-WingetCli
Write-Host "OK - SetupWinget completed."
}
elseif ($UpgradeAll.IsPresent) {
Write-Host "INFO - Running in UpgradeAll mode."
Invoke-WingetUpgradeAll
}
elseif ($Apps -and $Apps.Count -gt 0) {
Write-Host "INFO - Running in Apps-install mode for $($Apps.Count) app(s)."
Invoke-WingetInstallForApps -AppIds $Apps
}
else {
Write-Host "ERROR - No valid parameters provided. Use -SetupWinget or -Apps <ids>."
exit 1
}