Reputation: 11
Can someone assist me in how can I search all of AD for a users, who I would not know if exist or not.
Root domain (NA1.local)
Resource Domain (domain1.local, domain2.local, domain3.local)
MSmith (not sure where in the domain he\she is located or if the userid has been deleted from AD) $user = PSmith
foreach ($domain in $domains)
{
Get-ADUser -Identity $username -Server $domain -ErrorAction SilentlyContinue
if ($? -eq 'True') {
$forest = Get-ADUser $username -Server $domain
Add-ADGroupMember -Identity $GPName -Member $forest -Server $VbrickSrv }
}
Upvotes: 1
Views: 4061
Reputation: 1248
As well as what @Adam said about using a filter rather than a where
clause (which is the proper answer) , you can simplify your code a bit when you find the user
foreach ($domain in $domains) {
If ($u = Get-ADUser -Filter 'SamAccountName -eq "psmith"' -server $domain) {
Add-ADGroupMember -Identity $GPName -Members $u -Server $domain
Break #this should exit from the foreach loop
}
}
Upvotes: 0
Reputation: 4168
Specify the username with the -Filter
or -LDAPFilter
vs. the -Identity
parameter. The filters are usually faster because they do the filtering on the DC instead of locally on the machine running the script. Also, the cmdlet won't generate an exception if nothing is returned when using the filter (over the identity) parameters.
$user = Get-ADUser -Filter { SamAccountName -eq 'psmith' }
...
I normally tell you to set the search base to whatever makes sense for your search. The more restrictive the better, but I see you want to search the entire domain. Just keep that in the back of your mind.
Check the following article out for a deeper discussion.
Upvotes: 1