Help with a ForEach

Welcome Forums General PowerShell Q&A Help with a ForEach

This topic contains 4 replies, has 4 voices, and was last updated by

 
Participant
1 month, 2 weeks ago.

  • Author
    Posts
  • #118926

    Participant
    Points: 74
    Rank: Member

    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

  • #118942

    Participant
    Points: 245
    Helping Hand
    Rank: Participant

    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.

  • #118974

    Moderator
    Points: 171
    Team MemberHelping Hand
    Rank: Participant
    
    $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
    }
    
    
  • #119013

    Participant
    Points: 110
    Helping Hand
    Rank: Participant

    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.

    $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
    

     

  • #119038

    Participant
    Points: 74
    Rank: Member

    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

You must be logged in to reply to this topic.