using get-aduser command in Powershell

Hi there,

I need some help on how to pass a powershell variable to get-aduser account. For example,

I can run this successfully:

get-aduser -filter {name -like “smith”} | select SamAccountName

but if I am reading a bunch of names for a file, then I need to be able to pass the names as a variable, like this as an example:

$username=“smith”

get-aduser -filter {name -like “$username”} | select SamAccountName

doesn’t work, I think the variable doesn’t get resolved. Any ideas how to fix it. Thank you.

 

 

 

There are different ways to write a filter for AD
Try like so:

$username="smith"
get-aduser -filter "name -like '*$username*'" | select SamAccountName

Awesome, thank you Alex,

I tried:

‘name -like “$username”’

but not

“name -like ‘$username’”

I thought single comma in front of a variable causes it not to resolve, but I guess I was wrong.

Thanks again

 

You are correct as well as wrong.

Single quote will not resolve variables, but double quotes do, that means if the single quotes are inside double quotes, it will resolve.

See below on quoting rules, I suggest you to read this document.

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-5.0