简体   繁体   中英

Powershell - Get-aduser return no value using a $var

i'm using this command to query AD for usernames::

get-aduser -filter 'SamAccountName -like "trembto*"

The AD return me some result that comply with that search.

when I try to apply this line with a $var inside, I get no result:

$userloop = "trembto"
get-aduser -filter 'SamAccountName -like "$($userloop)*"'

I should get the same result but it always returning me nothing, no error message I tried may alternative for the var part but in vain.

Thank for helping me

Variable expansion will not happen when single quotes are used to create a string. You must use double quotes to create a string for variable expansion to occur. In your case, you need to use double quotes to create the filter string, and use single quotes around the expanded variable.

Change to this:

$userloop = "trembto"
get-aduser -filter "SamAccountName -like '$($userloop)*'"

You can see this behavior by inspecting the string you use for your filter parameter.

Test:

$userLoop = "trembto"
$filter = 'SamAccountName -like "$($userLoop)*"'

Output of $filter:

SamAccountName -like "$($userLoop)*"

Changed to:

$userLoop = "trembto"
$filter = "SamAccountName -like '$($userLoop)*'"

Outputs:

SamAccountName -like 'trembto*'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM