Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
function Get-CertInfoTcp {
[CmdletBinding()]
param (
[Parameter(Position = 0, Mandatory)]
[string] $ComputerName,
[Parameter(Position = 1)]
[int] $Port = 443,
[Parameter()]
[int] $Timeout = 3000,
[Parameter()]
[switch] $ReturnCertificate
)
try {
$tcpClient = New-Object -TypeName System.Net.Sockets.TcpClient
$iar = $tcpClient.BeginConnect($ComputerName,$Port,$null,$null)
$wait = $iar.AsyncWaitHandle.WaitOne($Timeout,$false)
if (!$wait) {
$tcpClient.Close()
Write-Warning 'Connection attempt timed out'
}
else {
$null = $tcpClient.EndConnect($iar)
if ($tcpClient.Connected) {
$tcpStream = $tcpClient.GetStream()
$sslStream = New-Object -TypeName System.Net.Security.SslStream -ArgumentList ($tcpStream, $false)
$sslStream.AuthenticateAsClient($ComputerName)
$certificate = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList ($sslStream.RemoteCertificate)
if ($ReturnCertificate) {
Write-Output $certificate
}
else {
Write-Output ([PSCustomObject] [Ordered] @{
IssuerCN = $certificate.Issuer.Split(', ',[System.StringSplitOptions]::RemoveEmptyEntries)[0].Split('=')[1]
SubjectCN = $certificate.Subject.Split(', ',[System.StringSplitOptions]::RemoveEmptyEntries)[0].Split('=')[1]
ValidFrom = $certificate.NotBefore
ValidTo = $certificate.NotAfter
})
}
$certificate.Dispose()
$sslStream.Close()
$sslStream.Dispose()
$tcpStream.Close()
$tcpStream.Dispose()
}
else {
Write-Warning "Unable to establish connection to $ComputerName on port $Port"
}
$tcpClient.Close()
}
}
catch {
Write-Warning $_.Exception.InnerException.Message
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.