#Connect-AzAccount

$fileName =  ".\2020-12-23 azure_appservice_certificates (3).csv" 

$subscriptions = Get-AzSubscription | Where-Object State -eq "Enabled"

class CertificateCheck {
    [string] $SubscriptionId = ""
    [string] $CertificateId = ""
    [string] $ResourceGroupName = ""
    [string] $SubjectName = ""
    [string] $ThumbPrint = ""
    [DateTime] $ExpirationDate 
    [double] $TotalDays 
    [string] $Comment = ""
}

[CertificateCheck[]]$Result = @()

$StartDate=(GET-DATE)
[CertificateCheck[]]$Result = @()
foreach ($subscription in $subscriptions)
{
    Set-AzContext -SubscriptionId $subscription.Id

    $certs = Get-AzResource -ResourceType Microsoft.Web/certificates -ExpandProperties -ApiVersion 2018-02-01 | Select * -Expand Properties 
    foreach ($cert in $certs) 
    {    
        $id = $cert.Id
        
        [CertificateCheck] $certificateCheck = [CertificateCheck]::new()

        $certificateCheck.SubscriptionId = $subscription.Id
        $certificateCheck.CertificateId = $id
        $certificateCheck.ThumbPrint = $cert.Properties.thumbprint
        $certificateCheck.ResourceGroupName = $cert.ResourceGroupName

        try 
        {
            $thumbprint = $certificateCheck.ThumbPrint

            $certificate = Get-AzWebAppCertificate -ResourceGroupName $certificateCheck.ResourceGroupName -Thumbprint $thumbprint -debug -verbose

            if ($null -eq $certificate) 
            {
                $certificateCheck.Comment = "Could not find certificate"
            } 
            else 
            {
                try 
                { 
                    $subjectname = $certificate.SubjectName
                    $certificateCheck.SubjectName = $subjectname

                    Write-Host "Subject name: $subjectname"

                    $EndDate=[datetime]$certificate.ExpirationDate
                    $certificateCheck.ExpirationDate = $EndDate
                    $span = NEW-TIMESPAN –Start $StartDate –End $EndDate
                    $certificateCheck.TotalDays = $span.TotalDays
                }
                catch {
                    $certificateCheck.Comment = "Could not find expiry for certificate"
                }
            }
        }
        catch 
        {
            $certificateCheck.Comment = "Could not load certificate"
        }

        $Result += $certificateCheck
    }
}

$Result | Export-Csv -Path $fileName -NoTypeInformation -Force

$Result | ft