I have a .CSV file with several column headings and I am taking the First Name and Last Name heading to find AD accounts. What I would like to do and cannot figure out is how to return names in the CSV that don’t have associated AD accounts. Here is my example where I check for the last 10 lines for testing and return the associated accounts with the name in AD:
$OUpath = ‘OU=Users and Workstations,DC=domain,DC=COM’
$csvdata = Import-CSV D:\Data\Example.csv -Delimiter “|” | Select FirstName,LastName -Last 10
foreach ($user in $csvdata) {
$userName = “$($user.FirstName) $($user.LastName)”
$adName = Get-ADUser -Filter “name -like ‘$userName’” -Properties Name -SearchBase $OUpath | Select Name
}
So, in the example $username variable contains the First and Last names from the CSV file and $adName returns the associated names with user accounts. Currently, $username has 10 names while $adName has 9 names. How can I return the name that’s in $username but not in $adName? Ultimately I’d like to output that name to a file.
Firstly, when posting code in the forum, please can you use the preformatted text </> button. It really helps us with readability, and copying and pasting your code (we don’t have to faff about replacing curly quote marks to get things working).
How to format code on PowerShell.org
As you’re aware, $adName has the results of your Get-ADUser query. If no users are found, then $adName won’t have any value.
So, all you need to do is clear $adName each time you run the loop, and then check if it still has no value after running the query:
$OUpath = 'OU=Users and Workstations,DC=domain,DC=COM'
$csvdata = Import-CSV D:\Data\Example.csv -Delimiter '|' |
Select-Object FirstName,LastName -Last 10
foreach ($user in $csvdata) {
$adName = $null
$userName = "$($user.FirstName) $($user.LastName)"
$adName = Get-ADUser -Filter "name -like '$userName'" -Properties Name -SearchBase $OUpath |
Select-Object Name
if (-not($adName)) {
$userName
}
}
1 Like
Ingenious! This seems to do the trick. Sorry for the formatting.
Thanks!
Instead of being sorry, simply click edit, highlight the code, and click the </> icon. 
2 Likes