Microsoft cloud engineer - SharePoint, Office 365, Azure, DotNet, Angular, JavaScript.
Microsoft cloud engineer - SharePoint, Office 365, Azure, DotNet, Angular, JavaScript.

PowerShell – Cache AD User Lookup

Given a filter value, this PowerShell function will query Active Directory to find a matching user object and store results in a memory cache.  By default “samAccountName” is used for filter.  Optional field name can be provided to filter by any field such as Manager, Mail, or DN. 

Cheers!  

shades_smile

 

 

Source Code

https://github.com/spjeff/spadmin/blob/master/lookupADUser.ps1

 

# DataTable cache
$cacheUsers = New-Object System.Data.DataTable("users")
$cols = @("DistinguishedName","Enabled","extensionAttribute4","Manager","Name","Mail","SamAccountName")
foreach ($col in $cols) {
	$cacheUsers.Columns.Add($col) | Out-Null
}


# Find user by any field
Function lookupADUser ($login, $optFieldName) {
    # Filter 
    $dv = New-Object System.Data.DataView($cacheUsers)
    $filter = "SamAccountName = '$login'"
    if ($optFieldName) {
        $filter = $filter.Replace("SamAccountName", $optFieldName)
    }
    $dv.RowFilter = $filter

    # Return from cache
    if ($dv.Count -gt 0) {
        # Found
	    return $dv
    } else {
        # Insert
        $cmd = "SamAccountName -eq '$login'"
        if ($optFieldName) {
            $cmd = $cmd.Replace("SamAccountName", $optFieldName)
        }
        $sb = [Scriptblock]::Create($cmd)
        $user = Get-ADUser -Filter $sb -Properties extensionAttribute4,manager,enabled,Mail
        if ($user) {
            $row = $cacheUsers.NewRow()
	        foreach ($col in $cols) {
		        $row[$col] = $user.$col
	        }
	        $cacheUsers.Rows.Add($row) | Out-Null
	        return $dv
        } else {
            return $null
        }
    }
}


# Search by userID
$sb = {lookupADUser "userID"}
measure-command $sb |ft

# Search by Email
$sb = {lookupADUser "first_last@company.com" "Mail"}
measure-command $sb |ft

# Search by DN
$sb = {lookupADUser "CN=First Last,OU=Regular,OU=Accounts,DC=company,DC=com" "DistinguishedName"}
measure-command $sb |ft

 

Screenshot

2017-01-27_14-18-07

© Copyright 2016
@ SPJeff

Return to Top ▲Return to Top ▲