I have a list of displaynames in a file (userlist.txt). I have a piece of powershell code that will loop thru that list check if that display name exists in AD. The output is either User does exists in AD or User does not exist in AD. Below is my code.
$Users = Get-Content “c:\AD Scripts\users.txt”
foreach ($User in $Users) {
if (Get-ADUser -Filter {displayName -like $User}){
Write-Host “$User does Exist in AD!”
}
else {
Write-Host "$User does not exist in AD"
}
}
I would like to output this to a csv file displaying the displayname AND samAccountName. If the display does not exists in AD, I would like to output N/A in the samAccountName field of the csv file. Any help is appreciated.
not use write-host for your output method - if you want to write screen may i kindly suggest using write-output - makes life easier all around. Write-host doesn’t always follow all the rules with outputting so it makes it easier in the long run to use write-output.
utilize try/catch to determine if your ad account is found and create objects based on what it found
I included below a sample of what this could look like. There are a few other permutations that this could take but this is a simple example building upon the work you already did.
Please let me know of any questions I can clarify!
Thanks for your quick reply. When hen I changed this code, it is missing data in the CSV. $Users file has 194 names. However, the $data output is only containing about 84 records. It is not populating any records with NA (apparently those are being left out).
The -Filter either returns a found record or nothing (NULL), it does not produce an error, which is why nothing is returned for the users that don’t have a matching name. If you use -Identity $user, then it would throw an error and a try\catch could be leveraged, but Identity would be better with SamAccountName or LDAP Path. You can try something like this to find the user and if they are not found generate a matching object.
You make a good point Rob - I tried it in my test environment with samaccount instead of displayname - and forgot to adjust for the filter. Doh - sometimes the quick and dirty has issues. I skipped over the displayname since I typically don’t use that to look up - thanks for catching my error there.