Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to enumerate the name, samaccountname, and domain that each user in my forest belongs to and write it to a text file.

The script that I have now is:

Import-Module ActiveDirectory

$domains = "", "", ""

ForEach ($d in $domains){

Get-ADUser -Filter * -ResultSetSize $null -Server $d -Properties name, samaccountname |
Select-Object name, samaccountname | out-file c:\users\mdmarra\desktop\users.txt -append


What I need is the value of $d at the end of each line as well so that the output looks like

name          samaccountname        domain
----          --------------        ------
Marra,Mark    mdmarra     
share|improve this question
Have you tried turning it off and on again? – Scott Pack Mar 1 '13 at 14:32
up vote 7 down vote accepted

That's something you can easily achieve with hashtables in Select-Object:

ForEach ($d in $domains){

Get-ADUser -Filter * -ResultSetSize $null -Server $d -Properties name, samaccountname |
Select-Object name, samaccountname, @{ Name = 'domain'; Expression = { $d }} | out-file c:\users\mdmarra\desktop\users.txt -append

share|improve this answer
Yep, that's perfect. – MDMarra Mar 1 '13 at 15:31

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.