Avatar of Uptime Legal Systems
Uptime Legal Systems
Flag for United States of America asked on

Issue with powershell script / List users in child domains

I have a forest with a number of domains under it, and I need a script that will crawl the directories of the child domains and list the users in each domain.  What I have is:

Import-Module ActiveDirectory
(Get-ADForest).domains | % {
Get-ADUser -filter * -SearchBase "$((Get-ADDomain).distinguishedname)" | Select Name, sAMAccountName | Export-CSV "C:\$_ User Accounts.csv" -nti
}

Open in new window


This works and will list users in the C:\ drive labeled to the child domains but in the text file the users are all from the root forest level.  

I've tried tweaking this but can't seem to get it to produce the results I need- am I missing something obvious here?  Any help is appreciated.
PowershellActive DirectoryMicrosoft Server OS

Avatar of undefined
Last Comment
Joshua Grantom

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Joshua Grantom

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
Raheman M. Abdul

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Joshua Grantom

Uptime Legal Systems

ASKER
I believe you are Josh!  Thanks again for your previous (and this reply).

I got around to testing on a larger forest and found that it was only listing the users from the top level but it looks like it was a minor change.   Thanks again for both of the answers.
Joshua Grantom

You're welcome!
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Joshua Grantom

Also, using this

$((Get-ADDomain).distinguishedname) will always return the domain that your user account is in, that was my fault, I didnt think that through.

Rahemans post is incorrect as well.

The proper way for the other script to work is this.

Import-Module ActiveDirectory
(Get-ADForest).domains | % {
Get-ADUser -filter * -SearchBase "OU=Accounts,$((Get-ADDomain -Server $_).distinguishedname)" -Server $_ | Select Name,sAMAccountName | Export-CSV "C:\$_ User Accounts.csv" -nti
}

Open in new window


I will post the revised script on the other post as well.