Add Column to CSV

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of ceem88 ceem88 3 years, 9 months ago.

  • Author
    Posts
  • #9912
    Profile photo of ceem88
    ceem88
    Participant

    Hello Guys

    I have a problem causing me headaches – any help is appreciated.

    I have a csv file with 3 headers:
    client-software-version, client-software, user
    11, Outlook, username
    (...)

    What I have worked up so far:

    $users = import-csv test.csv | select user
    $email = $users | select-object -ExpandProperty user -ErrorAction 0 | foreach {((get-mailbox $_).EmailAddresses | select-object -first 1).SmtpAddress}

    I want to add the $email array to the csv as an additional column. The problem is that not all of these users have mailboxes (Emailaddress) so therefore I need to delete those lines without a mailbox – any ideas how I can do this with a simple code?

    Thanks again

  • #9913
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    To make sure I understand the properly, you want to both add a new column to the CSV, and remove any rows for users that don't have an email address defined? If so, try this:

    Import-Csv -Path test.csv |
    ForEach-Object {
        $emailAddress = Get-MailBox $_ | Select-Object -ExpandProperty EmailAddresses | Select-Object -First 1 -ExpandProperty SmtpAddress
    
        if ($emailAddress -ne $null)
        {
            Add-Member -InputObject $_ -MemberType NoteProperty -Name EmailAddress -Value $emailAddress -PassThru
        }
    } |
    Export-Csv -Path new.csv -NoTypeInformation
    

    (Note: I haven't tested this code because I don't have an Exchange environment handy, but hopefully it either works as-is or helps you figure out a solution.)

  • #9919
    Profile photo of ceem88
    ceem88
    Participant

    Exactly, I will test this later at work and give you an update if it worked 🙂
    Thanks!

You must be logged in to reply to this topic.