Wildcards with 'Get-ADUser -Filter' and 'variable'


I have code as below:

$person = Read-host -Prompt "Please input login or name and surname"

Get-ADUser -Filter {(SamAccountName -like "*$person*") -OR (Name -like "*$person*")}

Without wildcards (asterix) looks, like it works correctly, but when I try to add asterix and quotes this code show nothing.

Does someone know why is that?

Best Regards



This is a frequently asked question. A filter parameter is actually a string. You can form it this way. -Or has lower precedence than -like, so you don’t need the parentheses:

Get-ADUser -Filter "SamAccountName -like '*$person*' -OR Name -like '*$person*'"

I don’t pretend to understand the black magic when a script block is converted into a string and then passed into get-aduser.

It works :slight_smile:

But this is really black magic…

Yeah with these filters it’s more like “see if it works this way…”