How to extract specific user info from AD.

This is my second post in this subreddit, so forgive me for not knowing if I can insert code. I have the following script that should achieve your goals too. It will also allow you to get accurate "last logon" info. Save it as a .ps1:

<# .Synopsis Searches ActiveDirectory and returns a user-specified list of properties .DESCRIPTION This script takes a user-specified list OUs and a user-specified list of desired properties. .NOTES Author: Mike Hashemi V1 date: 15 August 2014 V2 date: 6 October 2014 - Converted the main part of the script, into a function. - Added routie to gather all DCs in a domain, for the ability to return LastLogonDate. .LINK

.PARAMETER DomainName Default value is 'company.local'. This parameter represents the DNS domain name, of the domain. .PARAMETER SearchPath Default value is 'DC=company,DC=local'. This parameter represents a comma-separated list of OUs to search. .PARAMETER OutputProperties Default value is 'Name,Enabled,LastLogonDate'. This parameter represents a comma-separated list of properties to return. .EXAMPLE .\get-ADUserProperties-Parameterized.ps1 This example get's a list of all users in 'DC=company,DC=local' and outputs the Name, Enabled, and LostLogonDate attributes. .EXAMPLE .\get-ADUserProperties-Parameterized.ps1 -SearchPath 'OU=emps,DC=company,DC=local','ou=accounting,DC=company,DC=local' This example get's a list of all users in the 'OU=emps,DC=company,DC=local' and 'ou=accounting,DC=company,DC=local' OUs and outputs the Name, Enabled, and LostLogonDate attributes. .EXAMPLE .\get-ADUserProperties-Parameterized.ps1 -SearchPath 'OU=emps,DC=company,DC=local' -OutputProperties Name,telephoneNumber | Export-CSV c:\users.csv -NoTypeInformation This example get's a list of all users in the 'OU=emps,DC=company,DC=local' OU and outputs the Name and Telephone Number attributes. The output is exported to a CSV.

>

[CmdletBinding()] param( [string]$DomainName = 'company.local',

[string[]]$SearchPath = 'DC=company,DC=local',

[string[]]$OutputProperties = 'Name,Enabled,LastLogonDate'

)

Function Get-TheUsers { #Create the hash table, for later. $props = @{}

Try {
    $dcs = Get-ADDomainController -Filter * -Server $DomainName
}
Catch [System.Security.Authentication.AuthenticationException] {
    Write-Error ("The domain, {0}, rejected the current credentials. Please enter a username and password for {0}." -f $DomainName)

    $dcs = Get-ADDomainController -Filter * -Server $DomainName -Credential (Get-Credential -UserName "$DomainName\" -Message "Enter domain admin credentials.")
}
Catch [Microsoft.ActiveDirectory.Management.ADServerDownException] {
    Write-Error ("It appears that {0} is unreachable. Please verify the DNS domain name of the desired domain (or DNS name resolution) and try again." -f $DomainName)
    Exit
}
Catch {
    Write-Error ("There was an unexpected error. The message is: {0}" -f $_.Exception.Message)
    Exit
}

Foreach ($ou in $SearchPath) {
    Write-Verbose ("Getting users in {0}" -f $ou)
    Foreach ($dc in $dcs) {
        If ($dc.OperatingSystem -like '*2003*') {
            Write-Warning ("Skipping {0}, because it is not a Server 2008 (or higher) DC." -f $dc.HostName)
        }
        Else {
            Write-Verbose ("Searching {0} on {1}." -f $ou,$dc.HostName)
            Try {
                $users = Get-ADUser -Filter * -SearchBase $ou -Properties $OutputProperties.Split(",") -Server $dc.HostName -ErrorAction Stop | Select $OutputProperties.Split(",")
            }
            Catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
                Write-Error ("Unable to search {0} because it appears to be a non-existent OU. The specific error message is: {1}" -f $ou, $_.Exception.Message)
                Exit
            }

            Foreach ($user in $users) {
                ForEach($property in $OutputProperties.Split(",")) {
                    $props.$property = $user.$property
                }
                New-Object PSObject -Property $props
            }
        }
    }
}

}

Try { If (!(Get-module ActiveDirectory )) { Import-Module ActiveDirectory -ErrorAction Stop } } Catch [System.IO.FileNotFoundException] { Write-Error ("Unable to load the required module. The specific message is: {0}" -f $_.Exception.Message) Exit }

$data = Get-TheUsers

Takes the output of the Get-ADUser query and groups by the first property in $OutputProperties, then uses the LastLogonDate property (if present)

to sort again and select only the last (most recent) entry.

Write-Verbose ("Sorting data.") $data | Group-Object Name | ForEach-Object {$_.Group | Sort-Object LogonTimeDate | Select-Object -Last 1}

/r/PowerShell Thread