Reputation: 17
I have problem with adding multiple users from different domains:
$nazwa = 'test'
$lista = Import-CSV "\test.csv"
ForEach ($user in $lista)
{Add-ADGroupMember -Identity $nazwa -Members $user.username}
I can type port, but don't have everything in main catalog, so Im using SAMAccountName to get users from other domains:
Get-ADUser -Server "test.pl:3268" -LDAPFilter "(SAMAccountName=$User.username)"
How can I use this domain with port to make ForEach correctly. Or do I have to search each domain separately?
Upvotes: 0
Views: 243
Reputation: 174485
do I have to search each domain separately?
Yes - but you don't necessarily have to query each domain for every single user.
LDAP's filter syntax supports |
(OR) clauses, so we can construct a filter that would match any of the usernames in question:
$filterClauses = $lista |ForEach-Object {
"(SAMAccountName=$($_.username))"
}
$ldapFilter = "(|$(-join $filterClauses))"
Now the $ldapFilter
string will look like (|(SAMAccountName=username1)(SAMAccountName=username2)(...))
, and we can do with a single query against each domain:
$userTable = @{}
foreach($domain in 'domain1.fqdn','domain2.fqdn','domain3.fqdn'){
Get-ADUser -Server "$domain`:3268" -LDAPFilter $ldapFilter |ForEach-Object {
$userTable[$_.SAMAccountName] = $_
}
}
At which point we can rewrite your loop to:
foreach($user in $lista){
if($userTable.ContainsKey($user.username)){
Add-ADGroupMember -Identity $nazwa -Members $userTable[$user.username]
}
else {
Write-Warning "No user with username $($user.username) was found!"
}
}
Upvotes: 2