Link to home
Start Free TrialLog in
Avatar of Cacophony777
Cacophony777

asked on

Using Variable in Get-ADUser Advanced Filter Search

Why doesn't this work?

$SearchExpression = "SamAccountName -like `"*smith*`""
Get-ADUser -F {$SearchExpression}

Open in new window


It works fine if i type in something specific instead of using the variable. Here is the error it throws out:

Get-ADUser : Error parsing query: '$SearchExpression' Error Message: 'syntax error' at position: '1'.
At line:1 char:11
+ Get-ADUser <<<<  -F {$SearchExpression}
    + CategoryInfo          : ParserError: (:) [Get-ADUser], ADFilterParsingException
    + FullyQualifiedErrorId : Error parsing query: '$SearchExpression' Error Message: 'syntax error' at position: '1'.
   ,Microsoft.ActiveDirectory.Management.Commands.GetADUser

Open in new window


Anybody have any ideas?

Thanks,
Cacophony
Avatar of footech
footech
Flag of United States of America image

The following should work.
$SearchExpression = "SamAccountName -like '*smith*'"

Open in new window

Of course you could take it even further with splatting.
$searchExpression = @{ filter = "SamAccountName -like '*smith*'"
          searchbase = "DC=some-ou,DC=domain,DC=com"
          properties = @("passwordlastset","title")
          }
Get-ADuser @searchExpression

Open in new window

Avatar of traoher
traoher

my guess is that you can't do it that way because "-like" is an operator.

you have to define like this:

$type='SamAccountName'
$matching='smith'

then your script becomes

get-ADuser -f {$type -like $matching}

This way you preserve the operator.
ASKER CERTIFIED SOLUTION
Avatar of footech
footech
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Cacophony777

ASKER

Didn't realize the brackets weren't necessary. Huh. Thanks for the help! ...I'll also have to look into this splatting thing... looks quite useful.