'Powershell certificate scripting using HttpClient

I am looking to use powershell to get certificate information from different API's using HttpClient. (Trying to write a script to find when certificates expire). I am so new to powershell and don't know where to start. From research I was trying the code below, but when using [Net.HttpWebRequest] it brings back a null for certificate when looking at $req.ServicePoint.Certificate. From [https://github.com/dotnet/runtime/issues/29301] this resource it looks like HttpWebRequest is outdated. Any suggestions on retrieving certificate information using powershell??

$timeoutMs = 10000
$sites = @("https://testsite1.com/")


Write-Host Checking $sites -f Green
$req = [Net.HttpWebRequest]::Create($sites)
$expDate = $req.ServicePoint.Certificate.GetExpirationDateString()


Solution 1:[1]

You can use TcpClient in dotnet core.

$hostname = 'www.google.com'
$ExpirationDays = 90
$request = [System.Net.Sockets.TcpClient]::new($hostname, '443')
$stream = [System.Net.Security.SslStream]::new($request.GetStream())
$stream.AuthenticateAsClient($hostname)
$effectiveDate = $stream.RemoteCertificate.GetEffectiveDateString() -as [datetime]
$expirationDate = $stream.RemoteCertificate.GetExpirationDateString() -as [datetime]
if ($expirationDate -lt [datetime]::UtcNow.AddDays($ExpirationDays)) {
    Write-Host "##vso[task.logissue type=warning] Update certificate for [$hostname]"
    $expiringObjectList += [pscustomobject] @{
        Hostname       = $stream.TargetHostName
        Thumbprint     = $stream.RemoteCertificate.Thumbprint
        Start          = [string]$effectiveDate
        End            = [string]$expirationDate
        ExpirationDays = (New-TimeSpan -Start (Get-Date) -End $expirationDate).Days
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dejulia489