From 60db65b5a626d545cfbc9005134f4bb805745f22 Mon Sep 17 00:00:00 2001 From: "Mr.k" Date: Thu, 2 May 2024 00:34:52 +0300 Subject: [PATCH] Fix Winget Detection by doing Proper Error Handling using a Try-Catch * Fix Winget Detection by doing Proper Error Handling using a Try-Catch * Remove unnecessary Variable Initialization of 'wingetFullVersion' Co-authored-by: Martin Wiethan <47688561+Marterich@users.noreply.github.com> * Add Comments to be make The Logic a Lot More Clear to Follow and Understand * Add Another Catch Statement with some 'Write-Warning' for Extra Information --- .../private/Test-WinUtilPackageManager.ps1 | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/functions/private/Test-WinUtilPackageManager.ps1 b/functions/private/Test-WinUtilPackageManager.ps1 index ca269fc3..291616b2 100644 --- a/functions/private/Test-WinUtilPackageManager.ps1 +++ b/functions/private/Test-WinUtilPackageManager.ps1 @@ -20,13 +20,22 @@ function Test-WinUtilPackageManager { $status = "not-installed" if ($winget) { - # Install Winget if not detected - $wingetExists = Get-Command -Name winget -ErrorAction SilentlyContinue - - if ($wingetExists) { - # Check Winget Version - $wingetVersionFull = (winget --version) # Full Version without 'v'. + # Check if Winget is available while getting it's Version if it's available + $wingetExists = $true + try { + $wingetVersionFull = winget --version + } catch [System.Management.Automation.CommandNotFoundException], [System.Management.Automation.ApplicationFailedException] { + Write-Warning "Winget was not found due to un-availablity reasons" + $wingetExists = $false + } catch { + Write-Warning "Winget was not found due to un-known reasons, The Stack Trace is:`n$($psitem.Exception.StackTrace)" + $wingetExists = $false + } + # If Winget is available, Parse it's Version and give proper information to Terminal Output. + # If it isn't available, the return of this funtion will be "not-installed", indicating that + # Winget isn't installed/available on The System. + if ($wingetExists) { # Check if Preview Version if ($wingetVersionFull.Contains("-preview")) { $wingetVersion = $wingetVersionFull.Trim("-preview")