Public/Update-specAppxProvisionedPackageRetention.ps1

function Update-specAppxProvisionedPackageRetention {
    <#
    .SYNOPSIS
        Updates the retention of specific AppX provisioned packages while removing others.
 
    .DESCRIPTION
        This function checks all provisioned AppX packages and retains those specified in the RetainList parameter.
        Any provisioned packages not in the RetainList will be removed.
 
    .PARAMETER RetainList
        An array of AppX package display names to retain.
 
    .EXAMPLE
        PS C:\> $retainApps = @('Microsoft.BingWeather', 'Microsoft.WindowsCalculator')
        PS C:\> Update-specAppxProvisionedPackageRetention -RetainList $retainApps
 
        This example retains the Microsoft Bing Weather and Windows Calculator AppX packages,
        while removing other provisioned packages.
 
    .EXAMPLE
        PS C:\> $retainApps = @('Microsoft.BingWeather', 'Microsoft.WindowsCalculator')
        PS C:\> Update-specAppxProvisionedPackageRetention -RetainList $retainApps -WhatIf
 
        This example shows what would happen if the function is executed without actually making any changes.
 
    .NOTES
        Author: owen.heaume
        Version: 1.0.0 - Initial release
    #>


    [CmdletBinding(SupportsShouldProcess = $true)]

    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $false)]
        [string[]]$RetainList
    )

    Begin {
        # get all provisioned packages
        $AppList = Get-AppxProvisionedPackage -Online
    }

    process {
        foreach ($app in $AppList) {
            # retain items in the list
            if ($RetainList -contains $app.DisplayName) {
                Write-Host "Retaining: $($app.DisplayName)" -ForegroundColor darkGreen
            } else {
                Write-Host "Removing: $($app.DisplayName)" -ForegroundColor Red

                if ($PSCmdlet.ShouldProcess($app.displayname, 'Remove-AppxProvisionedPackage')) {
                    try {
                        Remove-AppxProvisionedPackage -Online -PackageName $app.PackageName -ea stop
                    } catch {
                        Write-Error $_
                    }
                }
            }

        }
    }
}