Skip to content

Instantly share code, notes, and snippets.

@PanosGreg
Created March 11, 2026 11:29
Show Gist options
  • Select an option

  • Save PanosGreg/9fa821dc638189c4a0881001b3402280 to your computer and use it in GitHub Desktop.

Select an option

Save PanosGreg/9fa821dc638189c4a0881001b3402280 to your computer and use it in GitHub Desktop.
Get the certificate from an SSL-enabled service
function Get-SslCertificate {
<#
.EXAMPLE
Get-SslCertificate -Address devad2487dc3.ad.coupadev.net -Port 636
Check the Active Directory service on a domain controller to get the certificate we deployed for use by LDAPS
#>
[OutputType([System.Security.Cryptography.X509Certificates.X509Certificate2])] # <-- default output
[OutputType([System.Security.Cryptography.X509Certificates.X509Certificate])] # <-- fallback output
[CmdletBinding()] # if we can't convert it to X509Certificate2
param (
[Parameter(Mandatory)]
[string]$Address, # <-- for ex. www.mywebsite.com
[Parameter(Mandatory)]
[UInt16]$Port,
[int]$TimeoutSec = 3 # <-- default timeout is 3 seconds
)
$TcpClient = [System.Net.Sockets.TcpClient]::new()
$TcpClient.ReceiveTimeout = $TimeoutSec*1000
$TcpClient.SendTimeout = $TimeoutSec*1000
try {
$TcpClient.Connect($Address, $Port)
$TcpStream = $TcpClient.GetStream()
$CallbackDelegate = { param($DelegateSender, $DelegateCert, $DelegateChain, $DelegateErrors) return $true }
$LeaveInnerStreamOpen = $false
$SslStream = [System.Net.Security.SslStream]::new($TcpStream, $LeaveInnerStreamOpen, $CallbackDelegate)
try {
$SslStream.AuthenticateAsClient($Address)
$SslCert = $SslStream.RemoteCertificate
}
catch {
Write-Warning "Could not get the certificate from $Address"
throw $_
}
finally {
$SslStream.Dispose()
}
}
catch {
Write-Warning "Could not connect to $Address"
throw $_
}
finally {
$TcpClient.Dispose()
}
# output
try {
$out = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($SslCert)
Write-Output $out
}
catch {
Write-Warning 'Could not cast the received certificate to a certificate object. Will return the data as-is'
Write-Output $Certificate
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment