Private/Invoke-SystemAppxRebuild.ps1

function Invoke-SystemAppxRebuild {
    [CmdletBinding()]
    param ()

    # 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
        }
    }

    $appxCommand = "Get-AppXPackage -AllUsers | Foreach {Add-AppxPackage -DisableDevelopmentMode -Register `"$($_.InstallLocation)\AppXManifest.xml`" -ErrorAction SilentlyContinue}"

    Start-Process powershell.exe -Verb runAs -ArgumentList "-Command `"Try { $appxCommand } Catch { Write-Error $_.Exception.Message }`""

    # 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."
    }
}