Issue with trying to pass variable into [adsisearcher]

2.4k views Asked by At

I apologize in advance if this is something simple, but I've been researching for a few days now and unable to resolve on my own or find another route to explore.

Essentially I have the below which works and returns exactly what I need:

([adsisearcher]'(&(objectClass=user (samaccountname='*dland*'))').FindOne().Properties['samaccountname']    

which returns the username containing dland in it. I want to replace the dland with a variable ($usrNme1), but it errors out with "Unexpected token '$usrNme1'))'' in expression or statement."

I was able to get it working locally with using the ActiveDirectory module using the following:

Get-ADUser -Filter {SAMAccountName -like $usrNme1} | select-object -Property SAMAccountName    

But unfortunately I cannot use that against other computers in this environment and have to find another way and this is as far as I've gotten to finding a replacement.

Any assistance here would be greatly appreciated :) This is the last piece of the puzzle for me and its frustrating being so close and not being able to figure it out! Thanks in advance for taking the time :)

Edit: Forgot to comment, this script is going to be pushed out and run locally on windows 7 machines, which is part of the reason why I can't use Get-ADUser.

Thanks,

David

2

There are 2 answers

2
Matt On BEST ANSWER

Your query is a little malformed as it is missing a bracket after user but you can put variables in the string easily like in the following example. Variables placed inside double quotes will expand just fine* (Most of the time. Object parameters require subexpressions).

$accountname = "mcame*"
$query = "(&(objectClass=user)(samaccountname=$accountname))"
([adsisearcher]$query).FindOne().Properties['samaccountname']

Note: if you look at this question you will see issues doing the wildcard search that your are. If you have a large organization you might need to reconsider using leading and trailing asterices or whatever the plural is.

You original query

Aside from the bracket the reason it was not working was since you were using the single quotes. If you look at this resource it goes on to say

Comparative strings do NOT appear in quotation marks. A filter for the displayName 'Philipp Foeckeler' would read as follows: (displayName=Philipp Foeckeler).

Query should have worked without those inner quotes.

3
jbsmith On

Try this:

$foo = '*jsm*'
([adsisearcher]"(&(objectClass=user) (samaccountname=$foo))")