Brian R Brian R - 1 year ago 295
PowerShell Question

Get-ADUser fails when using a wildcard and variable in the same search string

I have a command to search for a user by their proxy email address.

Get-ADUser -Filter {ProxyAddresses -like "**"}

This command returns the record for the user I want and it works just fine.

I can also create a variable to store the exact string that will be found and search for that and I also get the correct result.

$email = ""
Get-ADUser -Filter {ProxyAddresses -like $email}

I don't want to do the above in the off chance that the record I am searching for is not smtp: (some may be sip or others).

However, I am iterating through a list of users so I need to look for $email instead of the actual string. I want to do this:

Get-ADUser -Filter {ProxyAddresses -like "*$email*"}

This returns $null. I can't figure out why. I've opened a new window and set $email equal to an address that I know works when I type it by itself, but the result is still $null.

I assume this has to do with adding the wildcards, but I can't figure out what the problem is.

Perhaps it is the quotation marks, since the following also fails:

Get-ADUser -Filter {ProxyAddresses -like "$email"}

I have always been able to use variables in strings before, so I don't understand why it fails.

Answer Source

My usual recommendation is to use -LDAPFilter rather than -Filter.

Get-ADUser -LDAPFilter "(proxyAddresses=*$email*)"

Internally, Get-ADUser must translate the -Filter to an LDAP filter anyway, and as you have seen, getting -Filter to work with embedded variables can be tricky.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download