Re-create expired Client Secret for a SharePoint Addin

There are moments when PHA’s client secrets expire.
If you generated the ClientId and ClientSecret using the /appregnew.aspx, then the secret will expire in 1 year.
The script below removes the current secrets and creates new ones valid for max. 3 years.

#Requires -RunAsAdministrator
if (!(get-module MSOnline)) {install-module MSOnline} else {Write-Host "MSOnline module already installed"}
Connect-MsolService #use your Office 365 account
$clientID = "12345678-1234-1234-1234-1234567890AB" #replace this with your client ID
$keys = Get-MsolServicePrincipalCredential -AppPrincipalId $clientId -ReturnKeyValues $true
Remove-MsolServicePrincipalCredential -KeyIds @($keys[0].KeyId.Guid,$keys[1].KeyId.Guid,$keys[2].KeyId.Guid) -AppPrincipalId $clientId
$bytes = New-Object Byte[] 32
$rand = [System.Security.Cryptography.RandomNumberGenerator]::Create()
$rand.GetBytes($bytes)
$rand.Dispose()
$newClientSecret = [System.Convert]::ToBase64String($bytes)
$dtStart = [System.DateTime]::Now
$dtEnd = $dtStart.AddYears(3)
New-MsolServicePrincipalCredential -AppPrincipalId $clientId -Type Symmetric -Usage Sign -Value $newClientSecret -StartDate $dtStart -EndDate $dtEnd
New-MsolServicePrincipalCredential -AppPrincipalId $clientId -Type Symmetric -Usage Verify -Value $newClientSecret -StartDate $dtStart -EndDate $dtEnd
New-MsolServicePrincipalCredential -AppPrincipalId $clientId -Type Password -Usage Verify -Value $newClientSecret -StartDate $dtStart -EndDate $dtEnd
Write-Host "The ClientID $clientID has the new Client Secret $newClientSecret"