Private/Invoke-UserAppxRebuild.ps1

function Invoke-UserAppxRebuild {
    [CmdletBinding()]
    param (
        [switch]$RestartExplorer
    )

    # Check if explorer.exe is running, stop the process if it is running
    if (Get-Process -Name explorer -ErrorAction SilentlyContinue) {
        # Stop explorer.exe and wait for it to stop, if it doesn't stop terminate the script
        try {
            Get-Process explorer | Stop-Process -Force -ErrorAction Stop
            $ExplorerStopped = $true
        }
        catch {
            Write-Error -Message "Failed to stop explorer.exe: $_"
            return
        }
    }

    Get-AppXPackage | ForEach-Object {
        Add-AppxPackage -DisableDevelopmentMode -Register "C:\Windows\SystemApps\Microsoft.Windows.Search_cw5n1h2txyewy\AppXManifest.xml" -ErrorAction SilentlyContinue
    }
    
    Get-AppxPackage | ForEach-Object {
        Add-AppxPackage -DisableDevelopmentMode -Register "C:\Windows\SystemApps\ShellExperienceHost_cw5n1h2txyewy\AppXManifest.xml" -ErrorAction SilentlyContinue
    }
    
    Get-AppXPackage | ForEach-Object {
        Add-AppxPackage -DisableDevelopmentMode -Register "C:\Windows\SystemApps\MicrosoftWindows.Client.CBS_cw5n1h2txyewy\AppXManifest.xml" -ErrorAction SilentlyContinue
    }

    if (-not (Get-AppxPackage Microsoft.AAD.BrokerPlugin)) {
        Add-AppxPackage -Register "$env:windir\SystemApps\Microsoft.AAD.BrokerPlugin_cw5n1h2txyewy\Appxmanifest.xml" -DisableDevelopmentMode -ForceApplicationShutdown  -ErrorAction SilentlyContinue
    }
    
    Get-AppxPackage Microsoft.AAD.BrokerPlugin
    
    if (-not (Get-AppxPackage Microsoft.Windows.CloudExperienceHost)) {
        Add-AppxPackage -Register "$env:windir\SystemApps\Microsoft.Windows.CloudExperienceHost_cw5n1h2txyewy\Appxmanifest.xml" -DisableDevelopmentMode -ForceApplicationShutdown  -ErrorAction SilentlyContinue
    }
    
    Get-AppxPackage Microsoft.Windows.CloudExperienceHost

    # Check if explorer was stopped by this script and output a message that it wasn't restarted
    if ($ExplorerStopped) {
        Write-Output "Explorer was stopped by this script but not restarted."
        Write-Output "If run as part of a task sequence it be restarted later."
    }

    # Check if explorer needs to be restarted and restart it
    if ($RestartExplorer) {
        # Start explorer.exe and wait for it to start, if it doesn't start terminate the script
        try {
            Start-Process explorer.exe -ErrorAction Stop
        }
        catch {
            Write-Error -Message "Failed to start explorer.exe: $_"
            return
        }
    }

}