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?
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.
@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?
“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.