Variable wildcard in Get-ADUser

I am sure this is just a syntax error, but I am trying to find AD users and I cannot understand why this is not working:

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

It just returns nothing. And I'm sure this is the syntax with the "*" symbol. but I don’t know why. Thanks for any help.

+4
powershell
source share
5 answers

$ x does not expand inside the Scriptblock filter, this should do the job:

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

Alternatively, you can use the ldap filter:

 Get-ADUser -LDAPFilter "(samaccountname=*$x*)" 
+8
source share

try just changing this:

 { SAMAccountName -like "*$x*" } 

Edit:

this should work:

 $x = '*' + $(Read-Host 'Enter name') + '*' get-aduser -Filter {name -like $x} -Properties DispalyName | FT -Properties DisplayName 
+1
source share

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 some other cases where double quotes will not save you, for example. with the 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 this case, use string formatting:

 PS H:\> Write-Host ("*{0}*" -f $psobj.s) *smith* 
+1
source share

Well, this works, a little slower:

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

The approach is slightly different, but it works no less! Thanks for all the help.

0
source share

I came across this in my powershell learning curve when using an object.

I read the user ID in the CSV file and needed to search / match / filter on them, and just like before double quotes, it didn’t work there.

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

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

The table had three columns "Name, ID, Department." To get them in the search filter for my 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 completely prevented my extension and quotation marks.

0
source share

All Articles