Powershell Needful Things put that in your pipeline

10May/114

Find SAMAccountName with trailing space

The other day, one of the security guys at a customer had a problem with a reporting package which needs to import objects from Active Directory via LDAP.

The process appeared to import a limited amount of user accounts and then stop.

Feedback provided by the vendor, stated that we had duplicate SAMAccountNames in the domain, which as you know is impossible.

I started investigating the issue, and found a number of objects which, at first appeared to have duplicate SAMAccountName properties. On further investigation, I found that some of these duplicates, were indeed similar, but ended in a trailing space.

I tested this, and it seemed that the ADUC does not allow you to create objects with trailing spaces, so these objects may have been imported from other directories, or old NT4 migrations etc.

I needed a way to find all the objects with trailing spaces in the SAMAccountName property to send the list to the administrators to fix, as this involved some human interaction which I am unable to script.

This seemed easy at first, once you realise that not all SAMAccountName properties are the same length!

The following script will use the Exchange Get-User cmdlet to determine the length of the SAMAccontName property, and then inspect the last character in the string to see if it is a space. If it is, it is added to a variable and reported at the end.

Hopefully this script saves you some time.

$broken = @{Name="Broken";expression={foreach-object {($_.SAMAccountName).ToString().SubString((($_.SAMAccountName.ToString().Length)-1),1).Contains(' ')}}}

$users = Get-User -Resultsize Unlimited

Foreach ($user in $users){
If (($user | Select $broken).broken -eq $True){
[array]$brokenAccounts += $user}
}

$brokenAccounts | Select Name, SAMAccountName, $broken
Comments (4) Trackbacks (0)
  1. You could also use RegEx, for example:
    Get-User -ResultSize Unlimited | ? { $_.samAccountName -match ” +$” }

    Regards,

    jfrmilner

  2. where do put his script, please brief on the steps.

    • Hi there, and thanks for the reply.

      You use this script from the Exchange management shell ,but you could apply the same method on Get-ADUser or even the Quest AD cmdlets.

      I hope this helps.


Leave a comment

No trackbacks yet.