Author Posts

February 28, 2014 at 1:02 pm

I am having an issue on adding a variable to my Get-ADComputer script.
This one is failing:
$PartialName = "3v1*"
Get-ADComputer -Filter 'Name -like "$PartialName"' | select -ExpandProperty Name

Here are the two ways I have been able to get it to work:
$PartialName = "3v1*"
Get-ADComputer -Filter "*" | ? {$_.Name -like "$PartialName"} | select -ExpandProperty Name

Or
$PartialName = "3v1*"
Get-ADComputer -Filter "Name -like ""$PartialName""" | select -ExpandProperty Name

What is the best way of doing this? Less resources, more efficient...etc?

February 28, 2014 at 1:05 pm

Well, there's mainly "the way that works."

In your first example, you're sending the literal $PartialName to Active Directory. It has no idea what to do with it. In your last example, by surrounding the filter in double quotes, you're allowing PowerShell to replace $PartialName with its contents, before sending the filter to AD. So that works.

Your second example is querying every single computer from AD and then filtering them locally. I suspect that will not perform as well as the second one.

February 28, 2014 at 2:06 pm

Did you try

$PartialName = "3v1*"

Get-ADComputer -Filter "Name -like '$PartialName'" | select -ExpandProperty Name

Alternatively use an LDAP filter – I think this should work & can't test it at the moment

Get-ADComputer -LDAPFilter "(cn=$PartialName)"

March 3, 2014 at 6:14 am

@Don Jones – That makes sense, I am just confused as why the variable wasn't working.

@Richard Siddaway – That worked like a champ. So I watched Jason Helmick and Jeffrey Snover, on the MVA PowerShell and he explained that you can put a variable in between "'s ("Here is $Variable") and it would stay a variable, and anything between the ' would be plain text. So why is this working?

Thank you both for helping me out with this.

March 3, 2014 at 6:33 am

“Name -like '$PartialName'” is a double-quoted string; any variables inside of it get expanded. The single quotes inside that string are just text; they don't receive any special treatment from PowerShell, and don't affect the behavior of variable expansion.

The reverse applies as well: 'Name -like "$PartialName"' is a single-quoted string. It doesn't matter that the string happens to contain double quotes; the variable is still not going to be expanded.

March 3, 2014 at 1:46 pm

@dave Wyatt – Thank you sir.