Custom export from ADUC

Hi there,

I have a code which reads names and exports the username from ADUC.

I wanted to create a simple condition (if statement) into my code to change username to “Not Found” if the full name has wrong spelling or that name does not exist in my ADUC.


This is currently my code:


Import-Module activedirectory
$displayname = @()
$names = get-content “c:\Scripts\fullnames.csv”
foreach ($name in $names) {

$displaynamedetails = Get-ADUser -filter { DisplayName -eq $name } -server “”| Select name,samAccountName

$displayname += $displaynamedetails


$displayname | Export-Csv “C:\Scripts\new\usernames.csv”


Could you please help me out here :slight_smile:





Please format you code as code using the code tag button (pre). Thanks

You may start with a little cleaner piece of code … maybe like this:

$NameList = Import-Csv -Path ‘c:\Scripts\fullnames.csv’
$Result = Foreach ($Name in $NameList) {
$ADUser = Get-ADUser -filter “DisplayName -eq ‘$name’” -server “
Name = $ADUser.Name
sAMAccountName = $ADUser.sAMAccountName

$Result | Export-Csv ‘C:\Scripts\new\usernames.csv’ -NoTypeInformation

If you have a proper CSV file as input you should use the proper cmdlet for the import. Of course you will have to adjust the code to fit you precondition. You may post some example lines of your CSV file (formatted as code as well, please).