Reputation: 23
I am running the attached script against my AD. I only need the script to return each AD account once, but it seems to be running in an infinite loop.
How do I stop this?
Thanks
Search-ADAccount -AccountExpired | foreach { get-aduser -Filter 'description -like "*leaver*"' }
Upvotes: 2
Views: 55
Reputation: 24081
The problem lies within too complex foreach loop and poorly filtered query. Let's take a closer look:
Search-ADAccount -AccountExpired | foreach { # 1
get-aduser -Filter 'description -like "*leaver*"' # 2
}
In the part #1, you'll get a list of all user and computer accounts that have expired. So far so good.
In the part #2, you pass one by one each expired account on the pipeline. Now, for every expired account found, you search AD for all user accounts that have description containing string leaver
. This makes no sense at all. (What's even worse, searching for a substring requires reading every object's description.)
As a concrete example, having 100 expired accounts and 1000 AD user accounts, the loop is doing 100*1000 search operations. Oops! No wonder it seems to take ages.
As working alternative, consider something like so (not tested on a real domain, so YMMV),
$expiredAccounts = Search-ADAccount -AccountExpired # 1
$expiredAccounts| foreach { # 2
get-aduser -Filter {samaccountname -eq $_.samaccountname -and description -like "*leaver*"} # 3
}
In the part #1, save the expired accounts in a variable. This makes no difference, but if these are needed later on, no need to re-search the AD.
In the part #2, pipe results onward. Nothing important here.
In the part #3, search the AD with much more effective filtering.
Upvotes: 4