Get-Package and Uninstall-Package

Hi,

I’ve googled and googled but cannot find anything. Do either of these have trappable return/exit codes/messages? E.g. Uninstall-Package failed or succeeded?

Thanks

ldoodle30,
Welcome back to the forum. :wave:t4: … long time no see. :wink:

It’s not specific to these particular cmdlets - it’s valid for almost all cmdlets … as you can read in the help

supports [<CommonParameters>] - just like almost any other proper PowerShell cmdlet. And in the help for

you can read about -ErrorAction … that’s where you should start. :+1:t4:

Thanks @Olaf

Here is my code:

    $result = Invoke-Command -ScriptBlock {
    
        try {
        
            $app | Uninstall-Package -Scope $Scope -Force | Out-Null
            Write-Log -Message "Uninstall State:       $appName was successfully uninstalled" -File $true -NewLine $true -Result "Default"
            $ExitCode = 0
            
        } catch {
        
            Write-Log -Message "Uninstall State:       $( $_.Exception.Message )" -File $true -NewLine $true -Result "Default"
            $ExitCode = 5002
            
        }
        
        return $ExitCode
        
    }

But Exception.Message doesn’t contain the output from Uninstall-Package if it fails. I can make it fail by launching from non-admin PowerShell so I get prompted for elevation to uninstall and press No, which cause the failure

Actually, I still get to the “uninstall success” line, which to me suggests pressing No to UAC prompt is not causing Uninstall-Package to really fail, so it’s not even hitting the Catch block

To make a catch block work properly and catch errors the errors have to be terminating. If the cmdlet you’re about to use does not generate a terminating error by default you have to force it either with using -ErrorAction 'Stop' directly as parameter or by setting the global preference variable $ErrorActionPreference = 'Stop'.

That’s the one! I was sure I have gotten around this before (with other cmdlets) but couldn’t remember how.

Thanks for the help :grinning:

With $_.Exception.Message, is there an equivalent to get an Error Code? Again I’m sure there is but cannot remember.