choooper2006
choooper2006

Reputation: 63

Powershell Get ADUser filter

I have an object called $data. I want to loop through that object to get ADUsers then do some work with that user. The problem I'm having is that the filter is not returning anything. Here is what I have.

foreach($object in $data)
{ 


    $ADuser = Get-ADUser -filter * -Properties * -SearchBase "$($object.ouPath)" |
               ? { $_.objectGUID -eq $object.GUID -and $_.employeeNumber -eq $object.personID } |
                Select-Object employeeNumber,
                    SamAccountName,
                    Enabled
    try
    {}
    catch
    {}
}

$data contains the following information:

personID : 9408
firstName : John
lastName : Doe
GUID : dde044a6-b11a-4c23-a4c3-7dfe798a98ce
ouPath : OU=test,DC=my,DC=domain

Upvotes: 0

Views: 879

Answers (1)

Theo
Theo

Reputation: 61028

If your query without the conditions in the Where-Object clause works, then there either is no user with that combination of attributes, OR you are mistaking EmployeeNumber with EmployeeID.

Also, getting all users first with all of their properties and filtering out the one user you seek after that is wasteful. Better use the -Filter parameter which gets things done way faster.

Something like:

foreach($object in $data) { 
    # check if you don't need the EmployeeID attribute instead of EmployeeNumber
    $filter = "ObjectGUID -eq '$($object.GUID)' -and EmployeeNumber -eq '$($object.personID)'"
    $ADuser = Get-ADUser -Filter $filter -Properties EmployeeNumber -SearchBase $object.ouPath -ErrorAction SilentlyContinue

    if ($ADuser) {
        # user found, do what needs to be done here. For demo, just output to console
        $ADuser | Select-Object EmployeeNumber, SamAccountName, Enabled
    }
    else {
        Write-Warning "Could not find user with ObjectGUID = '$($object.GUID)' and EmployeeNumber = '$($object.personID)'"
    }
}

Upvotes: 1

Related Questions