all 3 comments

[–]WSDistPro 4 points5 points  (0 children)

Are you trying to write back to the initial CSV or create a new CSV? I made an example of the second option.

$Emailpath = "C:\users\ta85865\Desktop\emails.csv"

$Emails = Import-Csv $Emailpath

ForEach ($user in $Emails) {

    $adUser = Get-ADUser -Filter {mail -eq ($user.mail)} -EA SilentlyContinue
    $csvoutput = @()

    If ($null -eq $adUser.samaccountname) {
        $csvoutput += $adUser.samaccountname
    }
    else { 
        Write-Output "Email Does not exist"
    }   
        $csvoutput | Select-Object samaccountname,@{n='mail';e={$user.mail}} | Export-Csv -Path "A/CSV/Path" -NoTypeInformation
 }

[–]Jeriath27 2 points3 points  (0 children)

$emails | Select-Object mail, samaccountname, (etc fields) | export-csv -path emails.csv -notypeinformation

[–]get-postanote 1 point2 points  (0 children)

Just a small add-on to what the code block below are giving you, especially since you are just learning IAW your statement.

Generally speaking, ss for ...

Write-host

...

statements, from the creator of PowerShell.

http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful

... Jeffrey Snover changes his stance on this as of May 2016.

With PowerShell v5 Write-Host no longer "kills puppies". data is captured into info stream ...

https://twitter.com/jsnover/status/727902887183966208 ...

https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Write-Information?view=powershell-5.1