Powershell Passing Variable to -Filter with Wild C

2020-05-02 00:05发布

问题:

I am having a hard time here on this one and I know its probably a simple syntax problem. I don't know how to pass this variable into the code chunk and have it acknowledged correctly.

$user = "Some.Person"

This works as I would expect.

get-aduser -filter {(Samaccountname -eq $user)}

This does not

get-aduser -filter {(userprincipalname -like $user*)}

tried with variations of "$user*", "'$user*'" as well as some others to no avail.

final outcome would be use like follows because we have AD accounts where UPN is different than UserName and I have a whole listing of Username formatted values I need to confirm still exist with active accounts.

Get-ADUser -Filter {(UserPrincipalName -like "$user*") -or (SamAccountName -eq "$user")} -SearchBase "" -Server "MyServer:3268"

回答1:

Strange behaviour, this is not THE answer but a turn arround ; personnaly, I use -LDAPFilter :

Get-ADUser -LDAPFilter "(userprincipalname=$user*)"

The polish notation for the filter is a bit disconcerting at the begining, but here, it's the natural way of filtering using the underlaying protocol LDAP.

Get-ADUser -LDAPFilter "(|(userprincipalname=$user*)(samAccountName=$user))"

You can get more information about this syntax in Search Filter Syntax, you can also get corresponding filters in About_ActiveDirectory_Filter.


If you really want to use the -Filter syntax you can do the following (I'am not so proud of that):

$userstar = "$user*"
Get-ADUser -Filter {(userprincipalname -like $userstar) -or (samAccountName -like $user)}