Replacing a string with a variable in Get-ADGroup

2.2k Views Asked by At

I'm trying to use PowerShell to search AD for Group Names.

Why don't either of these work, the param or the Read-Host? Both are passing strings, but the results are empty. However, if I replace the variable $ADGroup in the command with an actual Group Name (a string) and run the command Get-ADGroup... results are provided as expected. I tried to replace the double quotes with single quotes and I get the same results, the command works alone but neither Read-Host or param provide information. I can't figure out why the string isn't being passed when it's a variable ($ADGroup). Thanks.

param(
    [Parameter(Mandatory=$true)]
    [string]$ADGroup
)

# One or the other param or Read-Host

$ADGroup = Read-Host "Enter Group Name"

PS \> Get-ADGroup -Filter {name -like "*$ADGroup*"} -Properties * | Select-Object -Property Name

Get-ADGroup -Filter {name -like '*GroupName*'} -Properties * | Select-Object -Property Name

Name                                     
----                                     
Results
Results
Results
Results
Results
2

There are 2 best solutions below

0
Santiago Squarzon On BEST ANSWER

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.

2
NeoTheNerd On

maybe it doesn't recognize it as a string or the filter is not correct.

 param(
            [Parameter(Mandatory=$true)]
            [string]$ADGroup
            )
#one or the other param or read-host
$ADGroup = Read-Host "enter group name"
$ADGroup = $ADGroup.ToString()
Get-ADGroup -Filter {name -like "*$ADGroup*"} -Properties * | select -Property Name

or this should do it..

$ADGroup = $ADGroup.ToString()
Get-ADGroup -Filter {name -like "*$ADGroup*"} -Properties * | Select-Object -expandProperty Name