Powershell find users with similar family names

Hi,

I have a script that searches for users that have the exact Firstname I provide and Surnames that are alomst identical
So, when I provide the script the firstname "Sara" and surname "Smith", I want it to find al users that have names like:

Sara Smith
Sara Smithonian
Sara Smith Klein etc.

I'm using this line:
$names = $(try {Get-Aduser -filter * -Properties Surname | Where {$_.Givenname -like "$Givenname" -and $_.Surname -like "*$Lastname*"}} catch {$null})

I kind of works. It just finds only users that have the exact First and Surname I provide the script.
So, in the example above, it only finds all the "Sara Smiths" in AD, but not the Sara's with similar familynames.

How can I get this done ?
Thanks in advance.
LVL 2
LoyallAsked:
Who is Participating?
 
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
Variable substitution in expressions inside of -filter only works if you provide the filter as string, not as scriptblock:
$names = Get-ADUser -filter "(givenName -eq $GivenName) -and (surname -like '*$LastName*')"

Open in new window

and having a filter is definitely the better way to start a search.
1
 
Guy LidbetterCommented:
First off, it's more efficient to use the filter than to get everything and then find what you are looking for, also the surname field is canned so does not need to be included.

Ok, now this is kinda weird... It doesn't like the quotation marks... I got around it like this...

$GivenName = "Sarah"
$LastName = "*Smith*"
$names = Get-Aduser -filter {(givenName -like $Givenname) -and (surname -like $Lastname)}

Open in new window


If the Surname is a user input then I converted it like this

$Name = Read-host
$GivenName = "*" + $Name + "*"

Open in new window


And it seems to work....

Or I suppose when you feed the script a name... include the * in the input.. That would work too...
1
 
LoyallAuthor Commented:
I'm very sorry for my delayed response. I will test it tomorrow.
0
 
LoyallAuthor Commented:
My question has been answered
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.