tomohulk
tomohulk

Reputation: 612

Wildcard with variable in Get-ADUser

I'm sure this is just a syntax error, but I'm 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 DisplayName | FT -Properties DisplayName

Just doesn't return anything. I'm sure it is syntax with the "*", but I'm not sure why.

Upvotes: 7

Views: 90822

Answers (5)

Ernie
Ernie

Reputation: 1

I ran into this in my powershell learning curve when using an object.

I read in a csv file of user id's and needed to search/match/filter on them, and as put before double quotes did not work there.

My solution was to use ToString() method on my object and set it to a scalar variable then use that variable in the filter. Worked great.

$user_records=Import-CSV .\20140430.userids.csv

The table had three columns "Name, ID, Department". To get them in a search filter on their user id I used:

foreach ( $thisrow in $user_records ) {
$thisuser=$thisrow.Username.ToString()
Get-ADUser -Filter {SamAccountName -eq $thisuser} -SearchBase "OU=Domain Users,DC=topofthecharts,DC=com" -Properties Department 

}

This avoided my expansion and quotes troubles completely.

Upvotes: 0

Shay Levy
Shay Levy

Reputation: 126762

$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*)"

Upvotes: 18

CB.
CB.

Reputation: 60918

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

Upvotes: 2

tomohulk
tomohulk

Reputation: 612

Well, this works, just a little slow:

$x = Read-Host "Enter Name"

Get-ADUser -Filter * -Properties SAMAccountName | ? { $_.SAMAccountName -like "*$x*" } | Format-Table -Property SAMAccountName

Little differnt approach, but works non the less! thanks for all the help.

Upvotes: 0

Poorkenny
Poorkenny

Reputation: 1246

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*

Upvotes: 3

Related Questions