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.
$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*)"
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*
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With