Powershell Basics: Using Variables In ActiveDirectory Filters

When working with the ActiveDirectory PowerShell module, the -filter parameter is sometimes required to search for accounts or objects in Active Directory. Utilization of variables in those filters may also be required to return a needed value.

As an example, running the following command from the remote Exchange management shell returns an object that includes a username (called Alias in this example).

 $person = (Get-Mailbox ThmsRynr).Alias

While this value was easy to find (as it currently the only entry in the test directory) the next example will show how to pull the value using a filter.

 Get-AdUser -Filter "SamAccountName -eq $person"

However this method would result in the following error:

 Get-AdUser : Error parsing query: 'SamAccountName -eq ThmsRynr' Error Message: 'syntax error' at position: '20'.
At line:1 char:1
+ Get-AdUser -Filter "SamAccountName -eq $person"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ParserError: (:) [Get-ADUser], ADFilterParsingException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Microsoft.ActiveDirectory.Management.Commands.GetADUser

This is because the filter can’t handle the variable in that context. The filter needs to be wrapped in curly braces in order to use a variable in an ActiveDirectory cmdlet filter.

 Get-AdUser -Filter {SamAccountName -eq $person}

This will provide the following results:

 DistinguishedName : CN=Thomas Rayner,OU=Users,DC=lab,DC=workingsysadmin,DC=com
Enabled           : True
GivenName         : Thomas
Name              : Thomas Rayner
ObjectClass       : user
ObjectGUID        : <snip>
SamAccountName    : TFRayner
SID               : <snip>
Surname           : Rayner
UserPrincipalName : ThmsRynr@outlook.com

Adding the curly braces will now allow the filter to operate as needed.