How to GetSPN output to .csv

Miggy 21 Reputation points
2022-02-04T16:28:49+00:00

I have the below script, but having issues outputting to csv. Tried changing to write-output as well.

---# Source / credit:
---# https://social.technet.microsoft.com/wiki/contents/articles/18996.active-directory-powershell-script-to-list-all-spns-used.aspx

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

---## You can use this to filter for OU's:
---## $results = $search.Findall() | ?{ $_.path -like 'OU=whatever,DC=whatever,DC=whatever' }
$results = $search.Findall()

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 ""
}

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,381 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,091 Reputation points
    2022-02-04T19:47:38.06+00:00

    Try this (without using the old ADSI clutter):

    Get-ADObject -Filter 'servicePrincipalName -like "*"' -properties *|
        ForEach-Object{
            Write-Host "Object Name = " $_.name -backgroundcolor "yellow" -foregroundcolor "black"
            Write-Host "DN = "          $_.distinguishedName
            Write-Host "Object Cat. = " $_.objectCategory
            Write-Host "servicePrincipalNames"
            $i = 0
            ForEach ( $SPN in $_.servicePrincipalName ) {
                Write-Host "SPN(" (++$i) ") = " $SPN
            }
            Write-Host ""
        }
    

    To get all that into a CSV:

    Get-ADObject -Filter 'servicePrincipalName -like "*"' -properties *|
        ForEach-Object{
            $_ | Select-Object      @{n='Object Name';e={$_.name}}, 
                                    @{n="DN";e={$_.distinguishedName}},
                                    objectCategory,
                                    @{n="servicePrincipalNames";e={$_.servicePrincipalName -join ";"}}
        } | Export-Csv c:\junk\SPNs.csv -NoTypeInformation
    

    Note that because the number of SPNs may be different for each object it wouldn't do to place each SPN in a separate column. In this example I've placed them all into one column and separated each with a semi-colon.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful