How to Remove and Regenerate an Expired RDP Certificate using Custom Script Extension
Symptom:
Unable to connect to VM corrupt or expired RDP Certificate
Resolution:
Open up a Blank Notepad and paste the following into it:
#sets the Certificate Store path
$path = get-childitem -Recurse 'Cert:\LocalMachine\Remote Desktop'
#Check the certificate date
$path.NotAfter
#sets the thumbprint from the cert
$thumb = $path |Select-Object -ExpandProperty Thumbprint
#pulls just the Machine Key Name based thumbprint
$cert = $path.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
#Machine key properties based on the thumbprint
$key = Get-ChildItem C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys |Where-Object {$_.Name -eq $cert}
###destructive part###
#Removes the certificate
Remove-Item -path "Cert:\LocalMachine\Remote Desktop\$thumb"
#deletes the key
$key | % { $_.Delete() }
#reboot to generate a new cert
restart-service TermService -forceSave the file as RemoveMachineKeyCert.ps1
Navigate to the Azure Portal
Select the impacted VM
Select extensions
Select Add
Select Custom Script Extension
Select Create
Select the RemoveMachineKeyCert.ps1 created in the previous steps
Install the .ps1 file. No arguments are needed.
Go back to the extensions tab and wait for the Custom Script to report as successful
Restart the virtual machine so the certificate can be regenerated
Attempt to RDP to the machine.