Share via


Active Directory: PowerShell script to list all SPNs used

There are a lot of hints & tips out there for troubleshooting SPNs (service principal names).

Duplicate SPN?

Listing duplicate SPNs is fairly easy. Use the "setspn -X" command and you'll find out.

But how do you find out which SPNs are used for which users and computers are used for this?

SetSPN

Quite some scripts you find on the net assume you're looking for a specific SPN (HTTP/. ) or a specific user or a specific computer.

Like using setspn to find SPNs linked to a certain computer:

setspn -L <ServerName>

Like using setspn to find SPNs linked to a certain user account:

setspn -L <domain\user>

Ldifde

The old school system admins go for LDIFDE, like:

Ldifde -d "DC=Contoso,DC=Com" -l ServicePrincipalName -F C:\SPN.txt

or

Ldifde -f spnaccount.txt -r serviceprincipalname=*/servername* -l serviceprincipalname,samaccountname

What if, in a case where you need to clean up some SPNs, but the configuration is not documented.

The SPNs unknown, and the user accounts and server names are spread all over the place.

So you need a general script to list all SPNs, for all users and all computers.

Nice fact to know is SPNs are set as an attribute on the user or computer accounts.

So that makes it fairly easy to query for that attribute.

And modern admins do PowerShell, right?

Powershell

Here you go!

#Set Search

cls

$search = New-Object DirectoryServices.DirectorySearcher([ADSI]"")
 
$search.filter = "(servicePrincipalName=*)"
 
$results = $search.Findall()

#list results

foreach($result in $results)
 
{
 
       $userEntry = $result.GetDirectoryEntry()
 
       Write-host "Object Name = " $userEntry.name -backgroundcolor "yellow" -foregroundcolor "black"
 
       Write-host "DN      =      "  $userEntry.distinguishedName
 
       Write-host "Object Cat. = "  $userEntry.objectCategory
 
       Write-host "servicePrincipalNames"
 
       $i=1
 
       foreach($SPN in $userEntry.servicePrincipalName)
 
       {
 
           Write-host "SPN(" $i ")   =      " $SPN       $i+=1
 
       }
 
       Write-host ""
 
}

Screenshot


See also