DrixlRey
DrixlRey

Reputation: 245

Cannot export all users, only one shows up when Importing-CSV File to then Get-ADUser

I've only just started to learn PowerShell but I'm banging my head on the wall with this one. When I Import-CSV a list of users to get the userprincipalname on Get-Aduser with the header SamAccountName, I am able to see all the emails on the console:

ForEach ($user in $allUsers)
{ 
Get-ADUser $user.samaccountname -Properties userprincipalname | select -Property userprincipalname
}

However, when I try to export them to a csv-file only 1 user comes out. I always have a problem when using a foreach loop for this...

ForEach ($user in $allUsers)
{ 
Get-ADUser $user.samaccountname -Properties userprincipalname | select -Property userprincipalname | export-csv $path -NoTypeInformation
}

I'm always run into this problem when making my foreach loops. I only ever get or change 1 variable. Why is this? x_X Please help!

And my CSV file has a header of SamAccountName and samaccount names. Without exporting I get good data from this code on the console:

[email protected] [email protected] etc...

Upvotes: 1

Views: 685

Answers (1)

TravisEz13
TravisEz13

Reputation: 2413

You were exporting in each iteration of the loop, which would overwrite the file. I haven't tried it but the changes below should work.

$allUsers  | Foreach-Object { 
    $user = $_ 
    Get-ADUser $user.samaccountname -Properties userprincipalname | select -Property userprincipalname 
} | export-csv $path -NoTypeInformation

You must use this syntax vs foreach(x in y) if you want to directly pipeline the results to export-csv

Upvotes: 0

Related Questions