Recently, I tried to find a way to update the automatic certificate for the RD Gateway service. Unfortunately, there are no ready-to-use cmdlets (no idea why Microsoft didn’t write them). In this case, I used Get-CimInstance and Invoke-CimMethod commands to achieve the goal.
The code below updates the certificate and restarts the service. Don’t forget the service restart drops all active connections so don’t do it during working hours.
#this is the powershell code
#Requires -RunAsAdministrator
#path to your pfx certificate
$cert_path='c:\temp\my_certificate.pfx'
#path to certificate location (always must be Local Machine -> My
$cert_location='Cert:\LocalMachine\my'
#RDGW requires certificate with private key so we use pfx
$Thumbprint=(Import-PFXCertificate -FilePath $cert_path -CertStoreLocation $cert_location).Thumbprint
$Cert = Get-Item -Path ($cert_location+'\'+$Thumbprint)
$CertHash = $Cert.GetCertHash()
#call certificate update with recently added certificate
Get-CimInstance -Namespace root/CIMV2/TerminalServices -ClassName Win32_TSGatewayServerSettings | `
Invoke-CimMethod -MethodName SetCertificate -Arguments @{CertHash = $CertHash}
#don't forget to restart RDGW service to apply changes
#CAUTION! Service restart drops all active connection to the server!
Restart-Service -Name TSGateway -Force
Useful links:
https://learn.microsoft.com/en-us/powershell/module/cimcmdlets/invoke-cimmethod?view=powershell-7.3
https://learn.microsoft.com/en-us/powershell/module/cimcmdlets/get-ciminstance?view=powershell-7.3
https://learn.microsoft.com/en-us/windows/win32/termserv/win32-tsgatewayserversettings
https://learn.microsoft.com/en-us/powershell/module/pki/import-pfxcertificate?view=windowsserver2022-ps
๐๐๐
๐ฌDiscuss or ask a question in the Telegram๐ฌ