functions/Test-Ssl.ps1

function Test-Ssl {
<#
.SYNOPSIS
Tests the SSL/TLS certificate of a specified host and port.
 
.DESCRIPTION
This function establishes an SSL/TLS connection to the specified host and port, verifies the certificate,
and returns $true if the certificate is valid and trusted, or $false otherwise. Detailed certificate
information and errors can be output via the Verbose stream.
 
.PARAMETER HostName
The hostname (e.g., domain name or IP address) of the remote server to test the SSL certificate against.
 
.PARAMETER Port
The TCP port used for the SSL connection. Defaults to 443.
 
.EXAMPLE
Test-Ssl -HostName "example.com"
 
Tests the SSL certificate of example.com on port 443.
 
.EXAMPLE
Test-Ssl -HostName "example.com" -Port 8443 -Verbose
 
Tests the SSL certificate of example.com on port 8443 and displays verbose output including certificate details.
 
.OUTPUTS
System.Boolean
 
.RETURNS
True if the SSL certificate is valid and trusted; otherwise, False.
 
.NOTES
Author: Jascha Vincke
Date: 2025-06-12
#>


    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]$HostName,
        [int]$Port = 443
    )
    Write-Verbose "Testing SSL certificate for $($HostName)"
    try {
        $tcpClient = New-Object Net.Sockets.TcpClient
        $tcpClient.Connect($HostName, $Port)

        $sslStream = New-Object System.Net.Security.SslStream($tcpClient.GetStream(), $false, {
            param ($senderObj, $certificate, $chain, $sslPolicyErrors)
            if ($sslPolicyErrors -eq 'None') {
                return $true
            } else {
                Write-Warning "SSL-Error: $sslPolicyErrors"
                return $false
            }
        })

        $sslStream.AuthenticateAsClient($HostName)

        $cert = $sslStream.RemoteCertificate
        $x509 = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $cert

        Write-Verbose "Certificate valid to: $($x509.NotAfter)"
        Write-Verbose "Issued for: $($x509.Subject)"
        Write-Verbose "Issued by: $($x509.Issuer)"

        $sslStream.Close()
        $tcpClient.Close()

        return $true
    } catch {
        Write-Warning "SSL connection error: $($_.Exception.Message)"
        return $false
    }
}