Repository navigation
Expand file tree
/
Copy pathstart.ps1
More file actions
1690 lines (1464 loc) · 64.1 KB
/
Copy pathstart.ps1
File metadata and controls
1690 lines (1464 loc) · 64.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
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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
Script di inizio che installa e configura WinToolkit.
.DESCRIPTION
Verifica, installa e configura alcuni software, per poi creare una scorciatoia di avvio di WinToolkit sul desktop.
.NOTES
Compatibile con PowerShell 5.1+
#>
# --- CONFIGURAZIONE GLOBALE ---
$script:AppConfig = @{
MsgStyles = @{
Success = @{ Icon = '✅'; Color = 'Green' }
Warning = @{ Icon = '⚠️'; Color = 'Yellow' }
Error = @{ Icon = '❌'; Color = 'Red' }
Info = @{ Icon = '💎'; Color = 'Cyan' }
}
# ============================================================================
# HEADER CONFIGURATION - Modifica qui per aggiornare titolo e versione
# ============================================================================
Header = @{
Title = "Toolkit Starter By MagnetarMan"
Version = "Version 2.5.4 (Build 28)"
}
URLs = @{
StartScript = "https://raw.githubusercontent.com/Magnetarman/WinToolkit/refs/heads/Dev/start.ps1"
WingetMSIX = "https://aka.ms/getwinget"
GitRelease = "https://api.github.com/repos/git-for-windows/git/releases/latest"
PowerShellRelease = "https://api.github.com/repos/PowerShell/PowerShell/releases/latest"
OhMyPoshTheme = "https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/atomic.omp.json"
PowerShellProfile = "https://raw.githubusercontent.com/Magnetarman/WinToolkit/Dev/asset/Microsoft.PowerShell_profile.ps1"
WindowsTerminalSettings = "https://raw.githubusercontent.com/Magnetarman/WinToolkit/Dev/asset/settings.json"
ToolkitIcon = "https://raw.githubusercontent.com/Magnetarman/WinToolkit/refs/heads/main/img/WinToolkit.ico"
TerminalRelease = "https://api.github.com/repos/microsoft/terminal/releases/latest"
WebInstaller = "https://magnetarman.com/WinToolkit-Dev"
}
Paths = @{
Logs = "$env:LOCALAPPDATA\WinToolkit\logs"
WinToolkitDir = "$env:LOCALAPPDATA\WinToolkit"
Temp = "$env:TEMP\WinToolkitSetup"
Packages = "$env:LOCALAPPDATA\Packages"
Desktop = [Environment]::GetFolderPath('Desktop')
wtExe = "$env:LOCALAPPDATA\Microsoft\WindowsApps\wt.exe"
wtDir = "$env:LOCALAPPDATA\Microsoft\WindowsApps"
}
Registry = @{
TerminalStartup = "HKCU:\Console\%%Startup"
}
WindowsTerminal = @{
DelegationTerminalClsid = "{E12F0936-0E6F-548E-A9F6-B20C69A27D17}"
DelegationConsoleClsid = "{B23D10C0-31E3-401A-97EF-4BB30B62E10B}"
}
WingetProcesses = @(
'WinStore.App',
'wsappx',
'AppInstaller',
'Microsoft.WindowsStore',
'Microsoft.DesktopAppInstaller',
'winget',
'WindowsPackageManagerServer'
)
UpdateServices = @('wuauserv', 'bits', 'cryptsvc', 'dosvc')
Layout = @{
Width = 65
}
}
# ============================================================================
# FUNZIONI DI UTILITÀ & SUPPORTO WINGET
# ============================================================================
function Test-VCRedistInstalled {
<#
.SYNOPSIS
Checks if Visual C++ Redistributable is installed and verifies the major version is 14.
#>
$64BitOS = [System.Environment]::Is64BitOperatingSystem
$checksPassed = 0
# Controlliamo sempre la versione 32bit (esiste sempre su tutti i sistemi)
$registryPath32 = 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x86'
$dllPath32 = "$env:windir\syswow64\concrt140.dll"
if ((Test-Path -Path $registryPath32) -and
((Get-ItemProperty -Path $registryPath32 -Name 'Major' -ErrorAction SilentlyContinue).Major -eq 14) -and
[System.IO.File]::Exists($dllPath32)) {
$checksPassed++
}
# Se il sistema è 64bit controlliamo ANCHE la versione 64bit
if ($64BitOS) {
$registryPath64 = 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64'
$dllPath64 = "$env:windir\system32\concrt140.dll"
if ((Test-Path -Path $registryPath64) -and
((Get-ItemProperty -Path $registryPath64 -Name 'Major' -ErrorAction SilentlyContinue).Major -eq 14) -and
[System.IO.File]::Exists($dllPath64)) {
$checksPassed++
}
}
# Su sistema 32bit: basta che sia presente la versione 32bit
# Su sistema 64bit: devono essere presenti ENTRAMBE le versioni 32 + 64 bit
$requiredChecks = if ($64BitOS) { 2 } else { 1 }
return $checksPassed -eq $requiredChecks
}
function Get-WinGetFolder {
<#
.SYNOPSIS
Trova la cartella di installazione ufficiale di Winget piu' recente.
#>
try {
$arch = if ([Environment]::Is64BitOperatingSystem) { "x64" } else { "x86" }
$wingetDir = Get-ChildItem -Path "$env:ProgramFiles\WindowsApps" -Filter "Microsoft.DesktopAppInstaller_*_*${arch}__8wekyb3d8bbwe" -ErrorAction SilentlyContinue |
Sort-Object { [version]($_.Name -replace '^[^\d]+_((\d+\.)*\d+)_.*', '$1') } -Descending | Select-Object -First 1
if ($wingetDir) {
return $wingetDir.FullName
}
return $null
}
catch {
return $null
}
}
function Get-WinGetExecutable {
<#
.SYNOPSIS
Ottiene il percorso valido di winget.exe, con fallback diretto.
#>
# Prova prima il percorso standard alias
$aliasPath = "$env:LOCALAPPDATA\Microsoft\WindowsApps\winget.exe"
if (Test-Path $aliasPath) {
return $aliasPath
}
# Fallback: percorso diretto nella cartella di installazione
$wingetFolder = Get-WinGetFolder
if ($wingetFolder) {
$exePath = Join-Path $wingetFolder "winget.exe"
if (Test-Path $exePath) {
return $exePath
}
}
return $null
}
function Test-WingetCompatibility {
<#
.SYNOPSIS
Verifica la compatibilità del sistema operativo con Winget.
#>
$osInfo = [Environment]::OSVersion
$build = $osInfo.Version.Build
if ($osInfo.Version.Major -lt 10) {
Write-StyledMessage -Type Error -Text "Winget non supportato su Windows $($osInfo.Version.Major)."
return $false
}
if ($osInfo.Version.Major -eq 10 -and $build -lt 16299) {
Write-StyledMessage -Type Error -Text "Windows 10 build $build non supporta Winget."
return $false
}
return $true
}
function Test-WingetFunctionality {
<#
.SYNOPSIS
Verifica che Winget sia presente nel PATH e funzioni correttamente.
#>
Write-StyledMessage -Type Info -Text "🔍 Verifica funzionalità Winget."
# Aggiorna il PATH per rilevare installazioni recenti
Update-EnvironmentPath
if (-not (Get-Command winget -ErrorAction SilentlyContinue)) {
Write-StyledMessage -Type Warning -Text "Winget non trovato nel PATH."
return $false
}
try {
# Usa --version: locale, immediato, non richiede connessione internet
$versionOutput = (& winget --version 2>$null) | Out-String
if ($LASTEXITCODE -eq 0 -and $versionOutput -match 'v\d+\.\d+') {
Write-StyledMessage -Type Success -Text "✅ Winget operativo (versione: $($versionOutput.Trim()))."
return $true
}
Write-StyledMessage -Type Warning -Text "Winget presente ma non risponde correttamente (ExitCode: $LASTEXITCODE)."
return $false
}
catch {
Write-StyledMessage -Type Warning -Text "Errore durante test Winget: $($_.Exception.Message)."
return $false
}
}
function Invoke-ForceCloseWinget {
<#
.SYNOPSIS
Closes the processes that actually block Appx installation.
Safe approach that avoids killing system-critical processes.
#>
Write-StyledMessage -Type Info -Text "Chiusura processi interferenti."
# Lista mirata dei processi che bloccano effettivamente l'installazione Appx
$interferingProcesses = $script:AppConfig.WingetProcesses
foreach ($procName in $interferingProcesses) {
Get-Process -Name $procName -ErrorAction SilentlyContinue |
Where-Object { $_.Id -ne $PID } | # Don't kill ourselves
Stop-Process -Force -ErrorAction SilentlyContinue
}
Start-Sleep 2
Write-StyledMessage -Type Success -Text "Processi interferenti chiusi."
}
function Invoke-StopUpdateServices {
<#
.SYNOPSIS
Sospende temporaneamente i servizi di Windows Update e correlati per evitare conflitti con Winget.
#>
Write-StyledMessage -Type Info -Text "Sospensione temporanea servizi Windows Update per evitare conflitti."
$services = $script:AppConfig.UpdateServices
foreach ($svc in $services) {
if (Get-Service -Name $svc -ErrorAction SilentlyContinue) {
Write-StyledMessage -Type Info -Text "Arresto servizio: $svc..."
Stop-Service -Name $svc -Force -ErrorAction SilentlyContinue
}
}
Write-StyledMessage -Type Success -Text "Servizi di aggiornamento sospesi correttamente."
}
function Invoke-StartUpdateServices {
<#
.SYNOPSIS
Ripristina i servizi di Windows Update e correlati.
#>
Write-StyledMessage -Type Info -Text "Ripristino servizi Windows Update."
$services = $script:AppConfig.UpdateServices
foreach ($svc in $services) {
if (Get-Service -Name $svc -ErrorAction SilentlyContinue) {
Write-StyledMessage -Type Info -Text "Avvio servizio: $svc..."
try {
Start-Service -Name $svc -ErrorAction Stop
}
catch {
# Ignora avvertimenti di avvio in corso e servizi delayed
if ($_.Exception.Message -notmatch 'in corso') {
Write-ToolkitLog -Level 'Warning' -Message "Avvio servizio ${svc}: $($_.Exception.Message)"
}
}
}
}
Write-StyledMessage -Type Success -Text "Servizi di aggiornamento ripristinati."
}
function Set-WingetPathPermissions {
<#
.SYNOPSIS
Applies PATH permissions and adds winget folder to PATH.
Based on asheroto's Apply-PathPermissionsFixAndAddPath.
#>
$wingetFolderPath = $null
try {
$wingetFolderPath = Get-WinGetFolder
}
catch { }
if ($wingetFolderPath) {
# Fix permissions
Set-PathPermissions -FolderPath $wingetFolderPath
# Add to system PATH
Add-ToEnvironmentPath -PathToAdd $wingetFolderPath -Scope 'System'
# Add user PATH with literal %LOCALAPPDATA%
Add-ToEnvironmentPath -PathToAdd "%LOCALAPPDATA%\Microsoft\WindowsApps" -Scope 'User'
Write-StyledMessage -Type Success -Text "PATH e permessi winget aggiornati."
}
}
function Repair-WingetDatabase {
<#
.SYNOPSIS
Esegue un ripristino completo del database e delle configurazioni di Winget.
#>
Write-StyledMessage -Type Info -Text "🔧 Avvio ripristino database Winget."
try {
# 1. Ferma i processi interferenti
Invoke-ForceCloseWinget
# 2. Pulizia cache locale di Winget
$wingetCachePath = "$env:LOCALAPPDATA\WinGet"
if (Test-Path $wingetCachePath) {
Write-StyledMessage -Type Info -Text "Pulizia cache Winget."
Get-ChildItem -Path $wingetCachePath -Recurse -Force -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -notmatch '\\lock\\|\\tmp\\' } |
ForEach-Object {
try {
Remove-Item $_.FullName -Force -Recurse -ErrorAction SilentlyContinue
}
catch {}
}
}
# 3. Rimuovi file di stato danneggiati (solo JSON)
$stateFiles = @(
"$env:LOCALAPPDATA\WinGet\Data\USERTEMPLATE.json",
"$env:LOCALAPPDATA\WinGet\Data\DEFAULTUSER.json"
)
foreach ($file in $stateFiles) {
if (Test-Path $file -PathType Leaf) {
Write-StyledMessage -Type Info -Text "Reset file stato: $file."
Remove-Item $file -Force -ErrorAction SilentlyContinue
}
}
# 4. Reset delle sorgenti Winget
Write-StyledMessage -Type Info -Text "Reset sorgenti Winget."
try {
$null = & winget.exe source reset --force 2>&1
}
catch {} # Ignora errori durante il reset
# 5. Reset completo del pacchetto AppInstaller (Cruciale per ACCESS_VIOLATION)
Write-StyledMessage -Type Info -Text "Reset pacchetto Microsoft.DesktopAppInstaller."
if (Get-Command Reset-AppxPackage -ErrorAction SilentlyContinue) {
Get-AppxPackage -Name 'Microsoft.DesktopAppInstaller' | Reset-AppxPackage 2>$null
}
# 6. Re-registrazione manifest AppInstaller
try {
$manifest = (Get-AppxPackage -Name 'Microsoft.DesktopAppInstaller' -ErrorAction SilentlyContinue).InstallLocation
if ($manifest) {
$manifestXml = Join-Path $manifest 'AppxManifest.xml'
if (Test-Path $manifestXml) {
Write-StyledMessage -Type Info -Text "Re-registrazione manifest: AppxManifest.xml."
Start-AppxSilentProcess -AppxPath $manifestXml -Flags '-DisableDevelopmentMode -Register -ForceApplicationShutdown' | Out-Null
}
}
}
catch { }
# 7. Riprova con il modulo WinGet se disponibile
try {
if (Get-Command Repair-WinGetPackageManager -ErrorAction SilentlyContinue) {
Write-StyledMessage -Type Info -Text "Esecuzione Repair-WinGetPackageManager."
Repair-WinGetPackageManager -Force -Latest 2>$null *>$null
}
}
catch {
if ($_.Exception.Message -match '0x80073D06' -or $_.Exception.Message -match 'versione successiva') {
Write-StyledMessage -Type Info -Text "Repair-WinGetPackageManager completato (versione superiore già presente)."
}
else {
Write-StyledMessage -Type Warning -Text "Modulo Riparazione fallito: $($_.Exception.Message)."
}
}
# 8. Applica permessi e refresh PATH
Set-WingetPathPermissions
Update-EnvironmentPath
# 9. Verifica che winget risponda
Start-Sleep 2
$testVersion = & winget --version 2>$null
if ($LASTEXITCODE -ne 0) {
Write-StyledMessage -Type Warning -Text "⚠️ Ripristino completato ma winget potrebbe non funzionare."
}
else {
Write-StyledMessage -Type Success -Text "✅ Database Winget ripristinato (versione: $testVersion)."
}
return $true
}
catch {
Write-StyledMessage -Type Error -Text "❌ Errore durante ripristino database: $($_.Exception.Message)."
return $false
}
}
function Test-WingetDeepValidation {
<#
.SYNOPSIS
Esegue un test approfondito di connettività e funzionalità di Winget.
#>
Write-StyledMessage -Type Info -Text "🔍 Esecuzione test profondo di Winget (ricerca pacchetti in rete)."
try {
# Testa connettività ai repository, integrità del DB locale e parser Winget
# Esegue ricerca diretta per ottenere ExitCode corretto
$searchResult = & winget search "Git.Git" --accept-source-agreements 2>&1
$exitCode = $LASTEXITCODE
# Check for access violation crash (0xC0000005 = -1073741819 or 3221225781)
if ($exitCode -eq -1073741819 -or $exitCode -eq 3221225781) {
Write-StyledMessage -Type Warning -Text "⚠️ Crash rilevato (ExitCode: $exitCode = ACCESS_VIOLATION). Tentativo ripristino avanzato."
# 1. Prova prima il ripristino DB + Reset Appx
$null = Repair-WingetDatabase
Write-StyledMessage -Type Info -Text "🔄 Ripetizione test dopo ripristino database."
Start-Sleep 3
$searchResult = & winget search "Git.Git" --accept-source-agreements 2>&1
$exitCode = $LASTEXITCODE
# 2. Se crasha ancora, prova la reinstallazione completa
if ($exitCode -eq -1073741819 -or $exitCode -eq 3221225781) {
Write-StyledMessage -Type Warning -Text "⚠️ Crash persistente. Avvio reinstallazione completa Winget."
$null = Install-WingetPackage -Force
Write-StyledMessage -Type Info -Text "🔄 Test finale dopo reinstallazione."
Start-Sleep 3
$searchResult = & winget search "Git.Git" --accept-source-agreements 2>&1
$exitCode = $LASTEXITCODE
}
}
if ($exitCode -eq 0) {
Write-StyledMessage -Type Success -Text "✅ Test profondo superato: Winget comunica correttamente con i repository."
return $true
}
# Logga i dettagli per debug
$errorDetails = $searchResult | Out-String
if ($errorDetails.Length -gt 200) {
$errorDetails = $errorDetails.Substring(0, 200) + "."
}
Write-StyledMessage -Type Warning -Text "⚠️ Test profondo fallito: ExitCode=$exitCode. Dettagli: $errorDetails."
return $false
}
catch {
Write-StyledMessage -Type Error -Text "❌ Errore durante il test profondo di Winget: $($_.Exception.Message)."
return $false
}
}
# ============================================================================
# FUNZIONI DI INSTALLAZIONE
# ============================================================================
function Get-WingetDownloadUrl {
<#
.SYNOPSIS
Recupera l'URL di download dell'ultimo asset di Winget CLI da GitHub.
#>
param([string]$Match)
try {
$latest = Invoke-RestMethod -Uri "https://api.github.com/repos/microsoft/winget-cli/releases/latest" -UseBasicParsing
$asset = $latest.assets | Where-Object { $_.name -match $Match } | Select-Object -First 1
if ($asset) {
return $asset.browser_download_url
}
throw "Asset '$Match' non trovato."
}
catch {
Write-StyledMessage -Type Warning -Text "Errore recupero URL asset: $($_.Exception.Message)."
return $null
}
}
function Install-WingetCore {
<#
.SYNOPSIS
Esegue l'installazione minima e dipendenze core di Winget.
#>
Write-StyledMessage -Type Info -Text "🛠️ Avvio procedura di ripristino Winget (Core)."
$oldProgress = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
$tempDir = "$env:TEMP\WinToolkitWinget"
if (-not (Test-Path $tempDir)) {
New-Item -Path $tempDir -ItemType Directory -Force *>$null
}
try {
# 1. Visual C++ Redistributable (usando test avanzato)
if (-not (Test-VCRedistInstalled)) {
Write-StyledMessage -Type Info -Text "Installazione Visual C++ Redistributable."
$arch = if ([Environment]::Is64BitOperatingSystem) { "x64" } else { "x86" }
$vcUrl = "https://aka.ms/vs/17/release/vc_redist.$arch.exe"
$vcFile = Join-Path $tempDir "vc_redist.exe"
Invoke-WebRequest -Uri $vcUrl -OutFile $vcFile -UseBasicParsing
$procParams = @{
FilePath = $vcFile
ArgumentList = @("/install", "/quiet", "/norestart")
Wait = $true
NoNewWindow = $true
}
Start-Process @procParams
Write-StyledMessage -Type Success -Text "Visual C++ Redistributable installato."
}
else {
Write-StyledMessage -Type Success -Text "Visual C++ Redistributable già presente."
}
# 2. Dipendenze (UI.Xaml, VCLibs) — Estrazione dal pacchetto ufficiale (Metodo Sicuro)
Write-StyledMessage -Type Info -Text "Download dipendenze Winget dal repository ufficiale."
$depUrl = Get-WingetDownloadUrl -Match 'DesktopAppInstaller_Dependencies.zip'
if ($depUrl) {
$depZip = Join-Path $tempDir "dependencies.zip"
try {
$iwrDepParams = @{
Uri = $depUrl
OutFile = $depZip
UseBasicParsing = $true
ErrorAction = 'Stop'
}
Invoke-WebRequest @iwrDepParams
# Estrazione e installazione mirata per architettura
$extractPath = Join-Path $tempDir "deps"
Expand-Archive -Path $depZip -DestinationPath $extractPath -Force
$archPattern = if ([Environment]::Is64BitOperatingSystem) { "x64|ne" } else { "x86|ne" }
$appxFiles = Get-ChildItem -Path $extractPath -Recurse -Filter "*.appx" | Where-Object { $_.Name -match $archPattern }
$dependencies = @()
foreach ($file in $appxFiles) {
Write-StyledMessage -Type Info -Text "Trovata dipendenza: $($file.Name)."
$dependencies += $file.FullName
}
}
catch {
Write-StyledMessage -Type Warning -Text "Impossibile estrarre o installare le dipendenze dallo zip ufficiale. Errore: $($_.Exception.Message)."
}
}
# 3. Winget Bundle
Write-StyledMessage -Type Info -Text "Download e installazione Winget Bundle (con dipendenze)."
$wingetUrl = Get-WingetDownloadUrl -Match 'Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle'
if ($wingetUrl) {
$wingetFile = Join-Path $tempDir "winget.msixbundle"
Invoke-WebRequest -Uri $wingetUrl -OutFile $wingetFile -UseBasicParsing
$deps = if ($dependencies) { $dependencies } else { @() }
if (Start-AppxSilentProcess -AppxPath $wingetFile -DependencyPaths $deps -Flags '-ForceApplicationShutdown') {
Write-StyledMessage -Type Success -Text "Winget Core installato con successo."
}
else {
throw "Installazione Winget Core fallita."
}
}
return $true
}
catch {
Write-StyledMessage -Type Error -Text "Errore durante il ripristino Winget: $($_.Exception.Message)."
return $false
}
finally {
if (Test-Path $tempDir) {
Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue
}
$ProgressPreference = $oldProgress
}
}
function Install-WingetPackage {
<#
.SYNOPSIS
Procedura completa di installazione e ripristino di Winget.
#>
param([switch]$Force)
Write-StyledMessage -Type Info -Text "🚀 Avvio procedura installazione/verifica Winget."
if (-not (Test-WingetCompatibility)) {
return $false
}
# Usa la funzione avanzata ForceClose
Invoke-ForceCloseWinget
try {
$oldProgress = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
# Pulizia temporanei
$tempPath = "$env:TEMP\WinGet"
if (Test-Path $tempPath) {
Remove-Item -Path $tempPath -Recurse -Force -ErrorAction SilentlyContinue
}
# Reset sorgenti se Winget esiste
if (Get-Command winget -ErrorAction SilentlyContinue) {
try {
$null = & "$env:LOCALAPPDATA\Microsoft\WindowsApps\winget.exe" source reset --force 2>$null
}
catch {}
}
if (-not (Get-Module -ListAvailable Microsoft.WinGet.Client) -or $Force) {
Write-StyledMessage -Type Info -Text "Installazione modulo Microsoft.WinGet.Client."
try {
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Confirm:$false -ErrorAction Stop *>$null
Install-Module Microsoft.WinGet.Client -Force -AllowClobber -Confirm:$false -ErrorAction Stop *>$null
Write-StyledMessage -Type Success -Text "Modulo WinGet Client installato."
}
catch {
Write-StyledMessage -Type Warning -Text "Modulo WinGet Client: $($_.Exception.Message)."
}
}
Import-Module Microsoft.WinGet.Client -ErrorAction SilentlyContinue
# Riparazione via modulo
if (Get-Command Repair-WinGetPackageManager -ErrorAction SilentlyContinue) {
Write-StyledMessage -Type Info -Text "Tentativo riparazione Winget (Repair-WinGetPackageManager)."
try {
Repair-WinGetPackageManager -Force -Latest 2>$null *>$null
Write-StyledMessage -Type Success -Text "Repair-WinGetPackageManager eseguito."
}
catch {
if ($_.Exception.Message -match '0x80073D06' -or $_.Exception.Message -match 'versione successiva') {
Write-StyledMessage -Type Info -Text "Repair-WinGetPackageManager ignorato (versione superiore già presente)."
}
else {
Write-StyledMessage -Type Warning -Text "Repair-WinGetPackageManager fallito: $($_.Exception.Message)."
}
}
Start-Sleep 3
}
# Fallback finale: installazione via MSIXBundle
if (-not (Get-Command winget -ErrorAction SilentlyContinue) -or $Force) {
Write-StyledMessage -Type Info -Text "Download MSIXBundle da Microsoft."
$msixTempDir = $script:AppConfig.Paths.Temp
if (-not (Test-Path $msixTempDir)) {
$null = New-Item -Path $msixTempDir -ItemType Directory -Force
}
$tempInstaller = Join-Path $msixTempDir "WingetInstaller.msixbundle"
$iwrParams = @{
Uri = $script:AppConfig.URLs.WingetMSIX
OutFile = $tempInstaller
UseBasicParsing = $true
ErrorAction = 'Stop'
}
Invoke-WebRequest @iwrParams
if (Start-AppxSilentProcess -AppxPath $tempInstaller -Flags '-ForceApplicationShutdown') {
Write-StyledMessage -Type Success -Text "Installazione Winget MSIX Bundle riuscita."
}
else {
Write-StyledMessage -Type Warning -Text "Installazione Winget MSIX Bundle fallita."
}
Remove-Item $tempInstaller -Force -ErrorAction SilentlyContinue
Start-Sleep 3
}
# Reset App Installer
Write-StyledMessage -Type Info -Text "Reset App Installer."
try {
Get-AppxPackage -Name 'Microsoft.DesktopAppInstaller' | Reset-AppxPackage 2>$null
}
catch {}
# Applica permessi PATH e registrazione (basato su asheroto)
Set-WingetPathPermissions
Start-Sleep 2
Update-EnvironmentPath
if (Get-Command winget -ErrorAction SilentlyContinue) {
Write-StyledMessage -Type Success -Text "✅ Winget installato e funzionante."
return $true
}
Write-StyledMessage -Type Error -Text "❌ Impossibile installare Winget."
return $false
}
catch {
Write-StyledMessage -Type Error -Text "Errore critico: $($_.Exception.Message)."
return $false
}
finally {
$ProgressPreference = $oldProgress
}
}
function Install-GitPackage {
<#
.SYNOPSIS
Verifica e installa Git con fallback a download diretto.
#>
Write-StyledMessage -Type Info -Text "Verifica installazione Git..."
Update-EnvironmentPath
if (Get-Command git -ErrorAction SilentlyContinue) {
Write-StyledMessage -Type Success -Text "Git già installato."
return $true
}
Write-StyledMessage -Type Info -Text "Installazione Git..."
# 1. Tentativo via winget (Prioritario)
if (Get-Command winget -ErrorAction SilentlyContinue) {
$result = Invoke-WingetCommand -Arguments "install Git.Git --accept-source-agreements --accept-package-agreements --silent"
if ($result.ExitCode -eq 0) {
Start-Sleep 3
Update-EnvironmentPath
if (Get-Command git -ErrorAction SilentlyContinue) {
Write-StyledMessage -Type Success -Text "Git installato via winget."
return $true
}
}
}
# 2. Fallback: download diretto da GitHub
try {
Write-StyledMessage -Type Info -Text "Fallback: Download Git da GitHub..."
$release = Invoke-RestMethod -Uri $script:AppConfig.URLs.GitRelease -UseBasicParsing
$asset = $release.assets | Where-Object { $_.name -like "*64-bit.exe" } | Select-Object -First 1
if (-not $asset) {
Write-StyledMessage -Type Error -Text "Asset Git 64-bit non trovato."
return $false
}
$tempDir = $script:AppConfig.Paths.Temp
if (-not (Test-Path $tempDir)) { New-Item -Path $tempDir -ItemType Directory -Force | Out-Null }
$installerPath = Join-Path $tempDir $asset.name
Invoke-WebRequest -Uri $asset.browser_download_url -OutFile $installerPath -UseBasicParsing
Write-StyledMessage -Type Info -Text "Esecuzione installer Git..."
$procParams = @{
FilePath = $installerPath
ArgumentList = @("/SILENT", "/NORESTART", "/CLOSEAPPLICATIONS")
Wait = $true
PassThru = $true
}
$process = Start-Process @procParams
Remove-Item $installerPath -Force -ErrorAction SilentlyContinue
if ($process.ExitCode -eq 0) {
Update-EnvironmentPath
Write-StyledMessage -Type Success -Text "Git installato con successo."
return $true
}
Write-StyledMessage -Type Error -Text "Installazione fallita. Codice: $($process.ExitCode)"
return $false
}
catch {
Write-StyledMessage -Type Error -Text "Errore installazione Git: $($_.Exception.Message)"
return $false
}
}
function Format-CenteredText {
<#
.SYNOPSIS
Formatta un testo centrato rispetto alla larghezza specificata.
#>
param(
[string]$Text,
[int]$Width = 80
)
$padding = [Math]::Max(0, [Math]::Floor(($Width - $Text.Length) / 2))
return (" " * $padding) + $Text
}
function Show-Header {
<#
.SYNOPSIS
Visualizza l'header grafico dello script con titolo e versione.
#>
param(
[string]$Title,
[string]$Version
)
Clear-Host
$width = $script:AppConfig.Layout.Width
Write-Host ('═' * $width) -ForegroundColor Green
@(
' __ __ _ _ _ ',
' \ \ / / | | | \ | |',
' \ \ /\ / / | | | \| |',
' \ V V / | | | |\ |',
' \_/\_/ |_| |_| \_|',
'',
$Title,
$Version
) | ForEach-Object { Write-Host (Format-CenteredText -Text $_ -Width $width) -ForegroundColor White }
Write-Host ('═' * $width) -ForegroundColor Green
Write-Host ''
}
function Write-StyledMessage {
<#
.SYNOPSIS
Scrive un messaggio formattato con timestamp, icona e colore, e lo salva nel log.
#>
param(
[ValidateSet('Info', 'Warning', 'Error', 'Success', 'Progress')]
[string]$Type,
[string]$Text
)
# FIX: Windows 11 Indentation Issue
if ([Environment]::OSVersion.Version.Build -ge 22000) { $Text = "`r$Text" }
$style = $script:AppConfig.MsgStyles[$Type]
$timestamp = Get-Date -Format "HH:mm:ss"
Write-Host "[$timestamp] $($style.Icon) $Text" -ForegroundColor $style.Color
# Mirror to log file
$logLevel = switch ($Type) {
'Success' { 'SUCCESS' }
'Warning' { 'WARNING' }
'Error' { 'ERROR' }
default { 'INFO' }
}
Write-ToolkitLog -Level $logLevel -Message $Text
}
function Start-ToolkitLog {
<#
.SYNOPSIS
Inizializza il file di log strutturato per un tool specifico.
#>
param([string]$ToolName)
# Pulizia residui transcript
try { Stop-Transcript -ErrorAction SilentlyContinue } catch {}
$dateTime = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
$logdir = $script:AppConfig.Paths.Logs
if (-not (Test-Path $logdir)) {
New-Item -Path $logdir -ItemType Directory -Force | Out-Null
}
$Global:CurrentLogFile = "$logdir\${ToolName}_$dateTime.log"
Start-Transcript -Path "$logdir\${ToolName}_$dateTime.transcript.log" -Append -Force | Out-Null
# Raccolta metadati
$os = Get-CimInstance Win32_OperatingSystem -ErrorAction SilentlyContinue
$psVer = $PSVersionTable.PSVersion.ToString()
$header = @"
[START LOG HEADER]
Start time : $dateTime
ToolName : $ToolName
OS : $($os.Caption) $($os.Version)
PSVersion : $psVer
ToolkitVersion : $($script:AppConfig.Header.Version)
[END LOG HEADER]
"@
try { Add-Content -Path $Global:CurrentLogFile -Value $header -Encoding UTF8 -ErrorAction SilentlyContinue } catch {}
}
function Write-ToolkitLog {
<#
.SYNOPSIS
Scrive una riga di log strutturata SOLO su file.
#>
param(
[ValidateSet('DEBUG', 'INFO', 'WARNING', 'ERROR', 'SUCCESS')]
[string]$Level = 'INFO',
[string]$Message
)
if (-not $Global:CurrentLogFile) { return }
$ts = Get-Date -Format "HH:mm:ss"
$clean = $Message -replace '^\s+', ''
# Rimuovi tutti i caratteri ANSI/colori prima di salvare su file
$clean = $clean -replace '\x1B\[[0-9;]*[a-zA-Z]', ''
$line = "[$ts] [$Level] $clean"
try { Add-Content -Path $Global:CurrentLogFile -Value $line -Encoding UTF8 -ErrorAction SilentlyContinue } catch {}
}
function Start-AppxSilentProcess {
<#
.SYNOPSIS
Installa AppX in background sopprimendo le barre di progresso native.
#>
param(
[string]$AppxPath,
[string]$Flags = '-ForceApplicationShutdown',
[string[]]$DependencyPaths = @()
)
$errFile = Join-Path $env:TEMP "AppxError_$([guid]::NewGuid()).txt"
$depString = ""
if ($DependencyPaths.Count -gt 0) {
$depString = "-DependencyPackagePath " + (($DependencyPaths | ForEach-Object { "'$($_ -replace "'", "''")'" }) -join ", ")
}
$cmd = @"
`$ProgressPreference = 'SilentlyContinue';
`$ErrorActionPreference = 'SilentlyContinue';
try {
Add-AppxPackage -Path '$($AppxPath -replace "'", "''")' $depString $Flags -ErrorAction Stop | Out-Null
}
catch {
if (`$_.Exception.Message -match '0x80073D06' -or `$_.Exception.Message -match 'versione successiva') {
exit 0
}
if (`$_.Exception.Message -match '0x80073CF9' -or ([Security.Principal.WindowsIdentity]::GetCurrent().IsSystem)) {
try {
Add-AppxProvisionedPackage -Online -PackagePath '$($AppxPath -replace "'", "''")' $depString -SkipLicense -ErrorAction Stop | Out-Null
exit 0
}
catch {
`$_.Exception.Message | Out-File '$errFile' -Encoding UTF8; exit 1
}
}
`$_.Exception.Message | Out-File '$errFile' -Encoding UTF8; exit 1
}
exit 0
"@
$encodedCmd = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($cmd))
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = "powershell.exe"
$psi.Arguments = "-NoProfile -NonInteractive -EncodedCommand $encodedCmd"
$psi.CreateNoWindow = $true
$psi.UseShellExecute = $false
$proc = [System.Diagnostics.Process]::Start($psi)
$proc.WaitForExit()
if ($proc.ExitCode -ne 0) {
if (Test-Path $errFile) {
$errMsg = Get-Content $errFile -Raw
Write-ToolkitLog -Level 'ERROR' -Message "AppX install failed ($AppxPath): $errMsg"
Remove-Item $errFile -Force -ErrorAction SilentlyContinue
}
return $false
}
return $true
}
function Update-EnvironmentPath {
<#
.SYNOPSIS
Ricarica le variabili PATH di sistema e utente nella sessione corrente.
#>
# Ricarica PATH da Machine e User per rilevare installazioni avvenute nel processo corrente
$machinePath = [Environment]::GetEnvironmentVariable('Path', 'Machine')
$userPath = [Environment]::GetEnvironmentVariable('Path', 'User')
$newPath = ($machinePath, $userPath | Where-Object { $_ }) -join ';'
# Aggiorna la sessione PowerShell corrente
$env:Path = $newPath
# Forza il refresh a livello di processo per i componenti .NET avviati successivamente
[System.Environment]::SetEnvironmentVariable('Path', $newPath, 'Process')
}
function Invoke-DownloadFile {
<#
.SYNOPSIS
Helper DRY per download file con gestione errori centralizzata.
#>
param(
[string]$Uri,
[string]$OutFile,
[switch]$Silent
)
try {
$iwrParams = @{
Uri = $Uri
OutFile = $OutFile
UseBasicParsing = $true
ErrorAction = 'Stop'
}
Invoke-WebRequest @iwrParams
return $true
}
catch {
if (-not $Silent) {
Write-StyledMessage -Type Warning -Text "Errore download: $($_.Exception.Message)"
}
return $false
}
}
function Add-ToEnvironmentPath {
<#
.SYNOPSIS
Aggiunge un percorso alla variabile d'ambiente PATH nello scope specificato.