Home > OS >  Replacing a string with a variable
Replacing a string with a variable

Time:11-27

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 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"
        
  Get-ADGroup -Filter {name -like "*$ADGroup*"} -Properties * | select -Property Name

PS C:\Windows\system32> Get-ADGroup -Filter {name -like 'GroupName'} -Properties * | select -Property Name

Name

Results
Results
Results
Results
Results 

CodePudding user response:

This is one of the reasons why using a scriptblock on the -Filter parameter of ActiveDirectory module cmdlets is not recommended.

-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.

  • Using query string:
Get-ADGroup -Filter "name -like '*$ADGroup*'"
  • Using LDAP query string:
Get-ADGroup -LDAPFilter "(name=*$ADGroup*)"

Note: Name is a default attribute returned by Get-ADGroup, there is no need to call all attributes (-Properties *) as this is highly inefficient.

CodePudding user response:

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

CodePudding user response:

If you try without the properties flag, do you get an error?

Get-ADGroup -Filter {Name -like "*$ADGroup*"} | Select-Object -expandProperty Name

or

Get-ADGroup -Filter {Name -like "*Admin*"} | Select-Object -expandProperty Name
  • Related