Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Exporting AD users' attributes to CSV file from a text file with only IDs in powershell

I’m using PowerShell, and I’m trying to export AD users’ attributes to a CSV file from a text file that contains only user IDs (samAccountName). The text file can contain any amount of user IDs.

The problem is that when I run the code I have, the file created only has 1 entry, and it’s always the last user in the list of users in the text file, regardless of the amount of users I try to get the info for.

The code I run is this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$Users = Get-Content "C:\IDs.txt" |
ForEach-Object {Get-ADUser -Identity $User -Properties * | Select Name,SamAccountName,Description,Title,DistinguishedName,Enabled | Export-Csv "c:\UserInfo.csv" -NoTypeInformation}

Thank you in advance for your help.

>Solution :

The following statement wouldn’t work:

$Users = Get-Content "C:\IDs.txt" | ForEach-Object {
    Get-ADUser -Identity $User -Properties * ....

Because $User is not defined, in a ForEach-Object loop, to refer to the current item from the pipeline, you should use $_ ($PSItem).

As for the likable cause you get the last element in your export, you have previously defined $User while testing your code, then you’re querying the same AD Object for each line in C:\IDs.txt and the export, since Export-Csv is inside the loop, is being overwritten over and over.

The steps to fix it are quite straight forward, just put Export-Csv as the last statement in your pipeline and change $User for $_:

$props = 'Name', 'SamAccountName', 'Description', 'Title', 'DistinguishedName', 'Enabled'
Get-Content "C:\IDs.txt" |
    ForEach-Object { Get-ADUser -Identity $_ -Properties $props } |
    Select-Object $props |
    Export-Csv "c:\UserInfo.csv" -NoTypeInformation

Also the assignment to $Users ($Users = ...) will be always null since the output from Get-ADUser is being directed to Export-Csv.

Lastly, since Get-ADUser can process identities from pipeline, no ForEach-Object is needed:

$props = 'Name', 'SamAccountName', 'Description', 'Title', 'DistinguishedName', 'Enabled'
Get-Content "C:\IDs.txt" | Get-ADUser -Properties $props |
    Select-Object $props |
    Export-Csv "c:\UserInfo.csv" -NoTypeInformation
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading