Aaron
Aaron

Reputation: 3325

How do I look up Active Directory from powershell with multiple variables?

$ADInfo = Get-ADUser -filter {Surname -Like $ntaccount1} | Sort-Object Name

$ADInfo `
    | Format-Table `
        @{ Name = "Full Name"; Expression = { $_.name } },
        @{ Name = "User ID"; Expression = { $_.samaccountname } } -Autosize;

This will only search the Directory by Surname (Last name) and then it outputs the full name and user id of the results. How do I have it look for every variable instead of just Surname? I want to mimic as if you were searching in the actual active directory program, but in powershell.

Upvotes: 0

Views: 495

Answers (1)

Matt
Matt

Reputation: 46680

I'm looking into other ideas but just to see if this is in the direction you are looking for I made up and LDAP filter for what I think the AD Find does

$searchString = "Matt"
get-aduser -LDAPFilter "(|(displayName=$($searchString)*)(sn=$($searchString)*)(givenName=$($searchString)*)(cn=$($searchString)*)(samaccountname=$($searchString)*))"

So this will search all of the properties in AD and return users if they match "Matt*". Following the same logic but making the seach more configurable to suit your needs. Results should be the same for both as written. This way you can add/remove properties to search for.

$searchString = "Matt"
$properties = "displayName","sn","givenName","cn","samaccountname"
$ldapFilter = "(|$($properties | ForEach-Object{"($_=$($searchString)*)"}))"

Get-Aduser -LDAPFilter $ldapFilter

Using Plain Filter

For whatever reason -LDAPFilter is not working for you. We can use similar logic to get -Filter working. The property names will change to match the PowerShell Filter

$searchString = "Matt"
$properties = "FirstName","LastName","Name","DisplayName","SamAccountName"
$Filter = ($properties | ForEach-Object{"($_ -Like '$searchString*')"}) -Join " -Or "

Get-Aduser -Filter $Filter

Upvotes: 1

Related Questions