Public/Get-PiHoleStats.ps1

function Get-PiHoleStats {
    <#
    .SYNOPSIS
    Gets Pi-hole statistics summary.
 
    .DESCRIPTION
    This function retrieves current statistics from the Pi-hole API using the /stats/summary endpoint.
 
    .PARAMETER BaseUrl
    The base URL of the Pi-hole instance (e.g., http://pi.hole or https://pi.hole).
 
    .PARAMETER Credential
    A PSCredential object containing the Pi-hole password and any username. $creds = Get-Credential -UserName admin
 
    .PARAMETER SkipCertificateCheck
    Skip SSL certificate validation. Useful for self-signed certificates.
 
    .EXAMPLE
    $creds = Get-Credential -UserName admin
    Get-PiHoleStats -BaseUrl 'http://pi.hole' -Credential $creds
 
    .EXAMPLE
    $creds = Get-Credential -UserName admin
    Get-PiHoleStats -BaseUrl 'https://pi.hole' -Credential $creds -SkipCertificateCheck
    #>


    param (
        [Parameter(Mandatory = $true)]
        [string]$BaseUrl,

        [Parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]$Credential,

        [switch]$SkipCertificateCheck
    )

    begin {
        # No validation needed - function now supports both HTTP and HTTPS
    }

    process {
        try {
            # Authenticate and get session data
            $sessionData = Connect-PiHole -BaseUrl $BaseUrl -Credential $Credential -SkipCertificateCheck:$SkipCertificateCheck

            # Prepare API request
            $url = "$BaseUrl/api/stats/summary"
            $headers = @{ 'X-FTL-SID' = $sessionData.SID }

            $invokeParams = @{
                Uri         = $url
                Method      = 'Get'
                Headers     = $headers
                ErrorAction = 'Stop'
            }

            if ($SkipCertificateCheck) {
                $invokeParams.SkipCertificateCheck = $true
            }

            $response = Invoke-RestMethod @invokeParams

            return $response
        }
        catch {
            Write-Error "Failed to retrieve Pi-hole stats: $_"
            if ($sessionData) {
                Disconnect-PiHole -BaseUrl $BaseUrl -Id $sessionData.ID -SID $sessionData.SID -SkipCertificateCheck:$SkipCertificateCheck
            }
        }
        finally {
            if ($sessionData) {
                Disconnect-PiHole -BaseUrl $BaseUrl -Id $sessionData.ID -SID $sessionData.SID -SkipCertificateCheck:$SkipCertificateCheck
            }
        }
    }

    end {
        # Nothing to clean up in the end block
    }
}