Last active
June 23, 2017 10:36
-
-
Save gravejester/6903b2f65cbf5f243d727f960963f64e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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