Morning guys,

I am trying to create a script which Imports a CSV which currently has just got a title ‘users’ and below is just their full names. So for Example

users
John Smith
Dean Winchester

I want to import it and check AD to see if they exist and if they do, export their SamAccountNames and EmailAddress to another CSV.

Is this possible? I’ve been trying to figure it out but I am not very good at Powershell to be honest and I’m just getting nowhere.

Thanks in advance.

7 Spice ups

Try something like this

Foreach ($User in (Import-Csv -Path c:\temp\Users.csv))

{

$User = $User.name

    Try {

        Get-ADUser -Filter {name -eq $User} -Properties EmailAddress | select samaccountname, emailaddress -ErrorAction Stop | Export-Csv c:\temp\CorrectUsers.csv -NoTypeInformation -Delimiter "," -Append

    }

    Catch {} # Do something in the catch block with users that dont exist in AD?

}

Hi,

Thanks for getting back to me,

I’ve tried running this script now, changed the csv path etc but when I run it nothing happens and no csv is outputted.

Doesn’t look like I’m getting an error messages either.

Any ideas?

Thanks,

Ignore me, I was the problem.

Thanks RickardW, sorted it.

1 Spice up

When querying AD with the filter parameter, you’ll get a $null response if the user doesn’t exist. PowerShell is also about objects, writing to a csv inside a foreach loop is not a good practice.

$Users = Import-Csv -Path "c:\temp\Users.csv"

$Results = $Users | ForEach-Object {
    $ADUser = Get-ADUser -Filter "name -eq '$($User.Name)'" -Properties EmailAddress

    if ($null -ne $ADUser) {
        $ADUser | Select-Object SamAccountName, EmailAddress
    }
}

$Results | Export-Csv -Path "C:\temp\CorrectUsers.csv" -NoTypeInformation
1 Spice up

@saidbrandon ​ You are right about writing to the csv inside the loop. I did to many things at once here at work so my bad :). But regarding fault tolerance in this case usernames from the csv not recognized by AD is very easy to pick up in the catch block for simple identification. Jacobs really did not requested any fault tolerance but $user just needs to be added to the catch block and he will see the names of which users that AD do not like.

Try catch blocks are for exceptions, and shouldn’t be used for normal program flow. In the example I provided, an else block can be added to the if to identify when a user isn’t found.

if ($null -ne $ADUser) {
    $ADUser | Select-Object SamAccountName, EmailAddress
} else {
    Write-Warning -Message "$($User.Name) not found in Active Directory"
}

The above example illustrates how to perform a lookup and output if found, or notify the user if not without using a try catch block. If your code needs to be read/understood by someone else, or you in a few months, it will be hard to tell what’s going on since you’re using exceptions for program flow and you won’t know what’s normal and what’s not.

1 Spice up