Replacing a string with a variable in Get-ADGroup

This is one of the reasons why using a script block based filter (-Filter {...}) on the cmdlets of the ActiveDirectory Module is not recommended.

The -Filter on the Parameter section of the Get-* cmdlets from ActiveDirectory Module states the following:

-Filter

Specifies a query string that retrieves Active Directory objects. This string uses the PowerShell Expression Language syntax. The PowerShell Expression Language syntax provides rich type-conversion support for value types received by the Filter parameter. The syntax uses an in-order representation, which means that the operator is placed between the operand and the value.

  • Query String:
Get-ADGroup -Filter "name -like '*$ADGroup*'"
  • LDAP Query String:
Get-ADGroup -LDAPFilter "(name=*$ADGroup*)"

Recommended Documentations for efficient Filtering:


Note: Worth mentioning, when querying Active Directory you will want to retrieve only the needed attributes from the AD Objects, specially when querying big Domains / Forests. Using -Properties * is a bad practice and also very inefficient, this will slow down your query as it is retrieving all available attributes of the objects being queried.

Leave a Comment