List SPNs in Active Directory using PowerShell

How to list SPNs in Active Directory using PowerShell. A Service Principal Name (SPN) is a service name that is registered in Active Directory, and is associated with a computer or user account (the security context in which the service runs).  The standard AD tools don't give you a good way to figure out where an SPN is registered, or list what SPNs are registered in your AD.


-->
To locate a specific SPN, check out our posts Finding an SPN in Active Directory using Perl and Finding an SPN in Active Directory using VBScript.

The PowerShell script below finds all SPNs in your domain of the service type that you specify.  In the example below, I have the service type set to "HTTP", so the script returns all of the HTTP/ SPNs.  The script uses the directorySearcher .Net class to find the accounts with HTTP/ SPNs.

$serviceType="HTTP"
$spns = @{}
$filter = "(servicePrincipalName=$serviceType/*)"
$domain = New-Object System.DirectoryServices.DirectoryEntry
$searcher = New-Object System.DirectoryServices.DirectorySearcher
$searcher.SearchRoot = $domain
$searcher.PageSize = 1000
$searcher.Filter = $filter
$results = $searcher.FindAll()
foreach ($result in $results){
 $account = $result.GetDirectoryEntry()
 foreach ($spn in $account.servicePrincipalName.Value){
  if($spn.contains("$serviceType/")){
   $spns[$("$spn`t$($account.samAccountName)")]=1;
  }
 }
}
$spns.keys | sort-object

5 comments:

Sameer said...

This works with no issues. Thanks

Anonymous said...

This is great, thank you. Works better than some more recent offerings I've found, since it finds user accounts (not just computer accounts) that have SPNs bound to them.

I just tweaked the DirectorySearcher to the newer syntax.

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

tnrdhd said...

AMAZING! Thank you very much, this saved me untold hours.

Anonymous said...

Great post. I found that when I copied the last line ($spns.keys ¦ sort-object) PowerShell didn't like the '¦', so I replaced it with the '|' character

Brian said...

Thanks, I fixed the last line of the script. Thought I fixed that years ago!

Post a Comment

Related Posts Plugin for WordPress, Blogger...