Link to home
Start Free TrialLog in
Avatar of MilesLogan
MilesLoganFlag for United States of America

asked on

Get SamAccountName from Name with Powershell

Hi EE

I have about 80k names that I need to pull the SamAccountName for each ..

The way below took like 20 mins and I stopped it .. it had only pulled for 2000 accounts .. Can someone help me on making this
better with PS? I know this is not the best way ..

$Name = get-content C:\:Powershell\Names.txt
 $Name | Foreach {

 get-qaduser -Name $_
 } | Select samaccountname,Name,canon* | Export-csv SamAccountnames.csv -nti
Avatar of Mohammed Khawaja
Mohammed Khawaja
Flag of Canada image

Have you tried dsquery.exe as it is faster.  Run the following:

squery * -filter "&(objectClass=person)(objectCategory=user)" -attr cn samaccountname -limit 0 > samaccounts.txt
Avatar of MilesLogan

ASKER

Hi Mohammed ..thank you for the tip .. Ideally I would like it to be PowerShell ..
I see you are using get-qaduser which is using Quest AD modules.  Do you Win2008 or Win2003?  If you have Win2008 or higher, you could try get-aduser which I have found to be faster.
Part of the problem is you're doing 80,000 LDAP sequential LDAP calls. So straight off the bat your efficiency sucks. You would be better off potentially doing 1 single LDAP call and bringing back all of the user accounts with the properties you want. I would do it more like this (I don't use the Quest cmdlets so you will need to modify for those).

$Name = get-content C:\:Powershell\Names.txt
Get-ADUser -Filter * -Properties CanonicalName | Where-Object {$Name -contains $_.sAMAccountName} | Select samaccountname,Name,canon* | Export-csv SamAccountnames.csv -nti

Open in new window


20 minutes for 2,000 users seems excessive though. I would look at the performance of your Domain Controllers or look at using something other than the Quest cmdlets if they perform so slowly (either the PowerShell cmdlets or just .NET LDAP lookup). In my testing I am able to pull back 150,000 objects in 3 minutes using the AD cmdlets and export them to CSV.
Thanks Learnctx ... This is definitely way better .. I appreciate the info ... If I only need the SAmAccountName in the outfile ..

how would you modify your script ?
ASKER CERTIFIED SOLUTION
Avatar of Aard Vark
Aard Vark
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you .. much better then what I was doing .