howradisit
howradisit

Reputation: 43

Get-ADUser for multiple users across different servers

Ok, so I have a bit of a conundrum. I have a list of users I'm trying to get information for, via AD and I've got a nice little script I've found to get those users (shown below). The only hiccup I have is there are two potential servers where the users could be coming from and I'm only seeing from the one server.

Get-Content \\C:\Users.txt |
foreach-object{
Get-ADUser -filter {SamAccountName -eq $_} -Properties "Name,EmailAddress" |
Select-Object SamAccountName,Name,EmailAddress} |
Export-CSV 'C:\Email Addresses.csv' -NoTypeInformation

The issue is that I'm not sure which server the users might be in. For the sake of simplicity, the servers can be labeled "Server1.com" and "Server2.com"

Would I need to do some kind of nested foreach? Is it also possible to list the server in the CSV, so it shows SamAccountName,Server,Name,EmailAddress? Would an If statement work? What would be the easiest thing to accomplish this?

Thanks.

Upvotes: 0

Views: 4403

Answers (1)

Daniel
Daniel

Reputation: 5112

Nested foreach is the way I usually go as I have yet to find a better way to query all of AD for this information.

If you know the servernames you can place them in an array and loop through them for each user object. If a user object is returned you can break out of the server loop and move on to the next user. I usually start with the quickest server that contains the majority of my users and then order the rest accordingly.

Code is something like this

$servers = @("Server1", "Server2", "Server3")

Get-Content "C:\Users.txt" |
ForEach-Object {
    foreach ($server in $servers) {
        $aduser = Get-ADUser -Filter "SamAccountName -eq '$_'" -Properties Name, Mail -Server $server | Select-Object SamAccountName, Name, Mail
        if ($aduser) {
            $aduser # send object down the pipeline
            break   # break out of server loop and move to next user
        }

    }
} | Export-Csv 'C:\temp\testemail.csv' -NoTypeInformation

Upvotes: 1

Related Questions