powershellfor-loopactive-directoryio-redirectiontxt

Mapping Multiple IDs to their Email Address in Active Directory and Outputting Results to a Single File


I am trying to find a method to map IDs of multiple users to their associated email addresses in Active Directory (AD), and subsequently append the outputs into a txt file, ultimately generating a single file with a list of email addresses. Via the following command leveraging PowerShell AD Tools, I can output the email address of a certain user:

$user= testID
Get-ADUser $user -server ml -Properties * | Select-Object mail

Now I'm trying to adapt this to work across multiple users, although the method I've come across does not append or concatenate each result to the txt file. Each new output when the loop iterates overwrites the contents of the existing text file.

$multiple_users = "testID1", "testID2", "testID3"
foreach ($multiple_user in $multiple_users){
    Get-ADUser $multiple_user -server ml -Properties * | Select-Object mail > ID_to_email.txt
    }

Any direction or insight, is much appreciated!

Thank you


Solution

  • Building on Abraham Zinala's helpful comment:

    The immediate fix is to replace > with >> inside your foreach loop:

    However, using >> inside a loop is best avoided, because it is:

    Therefore, it is preferable to use a pipeline with a single Out-File call / > operation that receives the output from all iterations in a streaming fashion:

    Note:

    $multiple_users | 
      ForEach-Object {
        Get-ADUser $_ -server ml -Properties mail |
          Select-Object mail
      } > ID_to_email.txt # Write ALL output to ID_to_email.txt
    

    Instead of > ID_to_email.txt, you could use | Out-File ID_to_email.txt instead; explicit use of Out-File is required in the following cases: