Search code examples
powershelladsi

Extract AD User information via ADSI


How can I get these properties for a user via ADSI LDAP, these are the properties from Get-ADUser, I need the equivalent for ADSI.

  • Enabled
  • PasswordNeverExpires
  • PasswordExpired
  • Name
  • SamAccountName
  • Mail
  • PasswordLastSet

My objective is to query the entire domain for all users and get these attributes.

I tried with the Get-ADUser cmdlet and it timed out when querying for the users.

Get-ADUser -Filter * -Properties enabled,PasswordNeverExpires,passwordexpired,Name,SamAccountName,mail,passwordla‌​stset -server sc |
   where {$_.Enabled -eq "True"} |
   where { $_.PasswordNeverExpires -eq $false } |
   where { $_.passwordexpired -eq $false } |
   Select Name,SamAccountName,mail,
          @{l='PasswordExpires';e={$_.passwordlastset+(Get-ADDefa‌​ultDomainPasswordPolicy).MaxPasswordAge}},
          @{l='DaystoExpire';e={(New-TimeSpan -Start (get-date) -end ($_.passwordlastset+(Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge)).days}}

The above command works on a couple of users but if I query a large set of users it gives invalid enumeration context.


Solution

  • The properties SamAccountName, Name, and Mail correspond to AD attributes of the same name. PasswordLastSet is derived from the attribute pwdLastSet. The other 3 properties (Enabled, PasswordNeverExpires, and PasswordExpired) are flags in the userAccountControl attribute.

    Use an adsisearcher object with an LDAP query to search AD for user objects, then build custom objects with the desired properties:

    $ACCOUNTDISABLE       = 0x000002
    $DONT_EXPIRE_PASSWORD = 0x010000
    $PASSWORD_EXPIRED     = 0x800000
    
    $searcher = [adsisearcher]"(&(objectClass=user)(objectCategory=person))"
    $searcher.FindAll() | % {
      $user = [adsi]$_.Properties.adspath[0]
      New-Object -Type PSCustomObject -Property @{
        SamAccountName       = $user.sAMAccountName[0]
        Name                 = $user.name[0]
        Mail                 = $user.mail[0]
        PasswordLastSet      = [DateTime]::FromFileTime($_.Properties.pwdlastset[0])
        Enabled              = -not [bool]($user.userAccountControl[0] -band
                               $ACCOUNTDISABLE)
        PasswordNeverExpires = [bool]($user.userAccountControl[0] -band
                               $DONT_EXPIRE_PASSWORD)
        PasswordExpired      = [bool]($user.userAccountControl[0] -band
                               $PASSWORD_EXPIRED)
      }
    }
    

    With that said, why do you want to go to all this trouble instead of simply using Get-ADUser to the same end?

    Import-Module ActiveDirectory
    
    $attributes = 'SamAccountName', 'Name', 'Mail', 'PasswordLastSet', 'Enabled',
                  'PasswordNeverExpires', 'PasswordExpired'
    
    Get-ADUser -Filter * -Properties $attributes | select $attributes