Remove errored apps in SPO

We have a client were they have installed some trial apps from the SharePoint store to their SPO tenant. Then they did something, I don't know what :-), and tried to remove the apps. That step failed and the apps got "stuck" in "Sorry something went wrong with adding the app." or "Something went wrong with removing the app".
We filed a service request with Microsoft Support. Their back end engineers were not able to remove the apps. But, there was a solution one of them told us. They have a PowerShell script that they use all the time to remove apps in "stucking" state, but they could not execute that script for us because it is not officially supported by Microsoft. So we had to do it ourselves.

For this script to work you need the App instance ID. Therefore open the settings of the app and choose "details".
Now copy the AppID from the URL
Now put the username, password, URL and App instance ID in this script and paste everything in a PowerShell window.


$UserName = ""  #Specify the Global Admin User name
$Password = Read-Host -Prompt "Enter the password" -AsSecureString
$Url = "" #Specify the Site Collection URL

$context = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
$context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $Password)

$AppInstanceid = New-Object Guid("App Instance Id")  #specify App Instance Id here
$appInst = $context.Web.GetAppInstanceById($AppInstanceId)