Home > front end >  Exporting multi-valued attributes to new lines on a CSV
Exporting multi-valued attributes to new lines on a CSV

Time:01-18

A bit of background on this.

I have approx 900 user accounts in active directory that are disabled and need to be deleted. They all have mailboxes attached, and to prevent these email addresses being recycled and reused for new users, I want to add each email address, along with any email aliases to a distribution group that essentially won't go anywhere.

I have a list of the FQDNs off all 900 users, and I have created a script in Powershell that will take my list, and then it will do a "for each" loop for each user. The script gathers their email addresses and then exports them to a CSV file.

The end goal is to have a long list of email addresses so that I can add them to the distribution group.

Because the emailaddresses attribute has multiple values, I'm finding that when it exports it to excel, it exports each email address to the same line, currently separated by a semicolon.

What I am looking to achieve, is for each individual email address to be listed on a brand new line on the export. Is this possible?

# Get list of users that we want to delete.
$Users = Get-Content "c:\temp\UsersToDelete.txt"

# For each user - find their email addresses and append them to a CSV.

foreach ($User in $Users) {
    Get-Mailbox -Identity "$User" | select @{Name=’emailaddresses’;Expression={$_.emailaddresses -join “;”}} | export-csv -append "c:\temp\CollectedEmailAddresses.csv"
    }

CodePudding user response:

You would need an inner loop for each value in the .emailaddresses property:

Get-Content "c:\temp\UsersToDelete.txt" | ForEach-Object {
    foreach($email in (Get-Mailbox -Identity $_).emailaddresses) {
        [pscustomobject]@{
            User  = $_
            Email = $email
        }
    }
} | Export-Csv "c:\temp\CollectedEmailAddresses.csv" -NoTypeInformation

Also your code would be more efficient moving Export-Csv as the last statement in your pipeline and removing -Append assuming this is a new file. Appending a CSV line per loop iteration is inefficient and only slowing down your script.

  • Related