Public/Get-SqlSpnDiscoveryEngine.ps1

# =============================================================================
# Script : Get-SqlSpnDiscoveryEngine.ps1
# Author : Keith Ramsey
# =============================================================================
# Change Log
# -----------------------------------------------------------------------------
# 2026-05-09 Keith Ramsey Phase 2 release polish - DR-202 standard header applied.
# =============================================================================
function Get-SqlSpnDiscoveryEngine {
    <#
    .SYNOPSIS
        Scans local Windows services for SQL Server identities and resolves their TCP ports.
    .DESCRIPTION
        Returns one row per discovered SQL service (engine, agent, named instances) with
        its run-as identity, the instance name, the resolved TCP port from the registry
        (not assumed to be 1433), and the current Windows service state.

        Useful for ad-hoc operator inspection ("what SQL services are running on this
        host, and what are they running as?") and as the data source for the interactive
        Start-SqlSpnManager flow.
    .EXAMPLE
        Get-SqlSpnDiscoveryEngine
    .EXAMPLE
        Get-SqlSpnDiscoveryEngine | Where-Object Status -eq 'Running' | Format-Table
    .OUTPUTS
        PSCustomObject per discovered service: ServiceName, AccountName, Instance, Port, Status.
    .NOTES
        Local discovery only. For remote inspection, run remotely via Invoke-Command
        or use Get-SqlSpnInfrastructure -ComputerName for a single named target.
    #>

    [CmdletBinding()]
    param()

    $services = Get-CimInstance -ClassName Win32_Service -Filter "Name LIKE 'MSSQL%'"

    foreach ($svc in $services) {
        $instance = if ($svc.Name -eq 'MSSQLSERVER') { 'MSSQLSERVER' }
            else { $svc.Name -split '\$' | Select-Object -Last 1 }
        $port = Get-SqlActualPort -InstanceName $instance

        [PSCustomObject]@{
            ServiceName = $svc.Name
            AccountName = $svc.StartName
            Instance    = $instance
            Port        = $port
            Status      = $svc.State
        }
    }
}