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
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.
Get-ADGroup -Filter "name -like '*$ADGroup*'"
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.