Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wildcard with variable in Get-ADUser

Tags:

powershell

Im sure this is just a syntax error, but im trying to search AD users, and I cannot figure out why this does not work:

Write-Host "Enter LastName or UserName:"
$x = Read-Host
Get-ADUser -Filter { SAMAccountName -like '*$x*' } -Properties DispalyName | FT -Properties DisplayName

Just doesnt return anything. And im sure it is syntax with the "*". but not sure why. Thanks for any help.

like image 984
tomohulk Avatar asked Oct 04 '12 12:10

tomohulk


3 Answers

$x is not expanded inside the Filter scriptblock, this should do the job:

$x = 'mini'
Get-ADUser -Filter "SamAccountName -like '*$x*'" -Properties DisplayName | ft DisplayName 

DisplayName
-----------
Administrator

Alternatively, you could use ldap filter:

Get-ADUser -LDAPFilter "(samaccountname=*$x*)"
like image 140
Shay Levy Avatar answered Oct 25 '22 00:10

Shay Levy


I agree with the above poster. Single quotes prevent variable expansion. Double quotes will work.

PS H:\> $s = "smith"
PS H:\> Write-Host '*$s*' 
*$s*
PS H:\> Write-Host "*$s*" 
*smith*

There are still some cases where double quotes won't save you, e.g. with an object.

PS H:\> $psObj = New-Object PsCustomObject
PS H:\> $psobj | Add-Member -MemberType noteproperty -name s -value "smith"
PS H:\> Write-Host $psobj.s
smith
PS H:\> Write-Host "*$psobj.s*"
*@{s=smith}.s*

In that case, use string formatting:

PS H:\> Write-Host ("*{0}*" -f $psobj.s)
*smith*
like image 31
Poorkenny Avatar answered Oct 25 '22 01:10

Poorkenny


try just changing this:

{ SAMAccountName -like "*$x*" }

Edit:

this should works:

$x = '*' + $(Read-Host 'Enter name') + '*'
get-aduser -Filter {name -like $x} -Properties DispalyName | FT -Properties DisplayName
like image 31
CB. Avatar answered Oct 25 '22 00:10

CB.