Help with a ForEach

I have a csv of a list of SamAccountNames. Several of these users have a blank EmailAddress Property. This is my code:

$Users = Import-Csv "C:\Users.csv"

foreach ( $User in $Users ) {
Get-ADUser -Properties * -Identity $User.SamAccountName | Where { $_.EmailAddress -eq $Null } | Select Name, SamAccountName | Export-Csv C:\Users\a033904\Documents\DeptNoEmail.csv }

If I remove the Export-Csv part and run it I get the desired results I need but with the Export-Csv in the Csv all I get is the last user of the imported Csv. Does that make sense to you? I don’t quite understand what is wrong. Any guidance would be greatly appreciated.

Rich

You have 2 options. Either you add the parameter -Append to your Export-CSV - but that slows down your code a lot - or you place your Export-CSV outside of your loop.

[pre]

$Users = Import-Csv “C:\Users.csv”

$Users | ForEach-Object -Begin {
$output=@()
} -Process {
$output += Get-ADUser -Identity $_.samaccountname | Select-Object Name, SamAccountName
} -End {
$output | Export-Csv C:\temp\DeptNoEmail1.csv -NoTypeInformation
}

[/pre]

You are recreating the Csv in the Export-Csv PowerShell cmdlet within the ForEach loop. It is overwritten each loop.

If you take it outside the loop, it can contain all user objects.

[pre]
$Users = Import-Csv “C:\Users.csv”

$UserObjects = foreach ($User in $Users) {
Get-ADUser -Properties * -Identity $User.SamAccountName |
Where-Object { $_.EmailAddress -eq $null } |
Select-Object Name, SamAccountName
}

$UserObjects | Export-Csv C:\Users\a033904\Documents\DeptNoEmail.csv
[/pre]

 

Thank you everyone for the help. Coming into work this morning my mind was not so scrambled trying to figure this out. This is what I ended up using.

Get-Content C:\Powershell\Scripts\O365\Migration\DeptUsers.txt | Get-ADUser -Properties * | Where { $_.EmailAddress -eq $Null } | Select Name, EmailAddress | Export-Csv C:\NoEmail.csv -NotypeInformation

Powershell can be a love hate relationship, but I have to say I do enjoy working through the problems.

 

Rich