Reputation: 351
I'm having trouble attaching a wildcard (the *
character) to the end of a variable that contains a string in both a -Filter
and a -LDAPFilter
for Get-ADcomputer
in PowerShell.
I've tried a few solutions that I'll highlight below that I couldn't get to work. $compName
will be the variable I'm trying to add a wildcard to.
$compArray += Get-ADComputer -Filter 'Name -eq "$compName' + '*"' -SearchBase "OU=Office,DC=workplace,DC=org" -ResultSetSize 5000 | Select -Exp Name;
*
on either side of my variable because I saw this seems to be a common thing for wild card searches but alas that didn't seem to provide a solution either.$compArray += Get-ADComputer -Filter 'Name -eq "*$compName*"' -SearchBase "OU=Office,DC=workplace,DC=org" -ResultSetSize 5000 | Select -Exp Name;
-LDAPFilter
. The first thing I tried in LDAP was another concatenation.$compArray += Get-ADComputer -LDAPFilter '(name=$compName' + '*)' -SearchBase "OU=Office,DC=workplace,DC=org" -ResultSetSize 5000 | Select -Exp Name;
*
around the entire variable but that didn't seem to work either.$compArray += Get-ADComputer -LDAPFilter '(name=*$compName*)' -SearchBase "OU=Office,DC=workplace,DC=org" -ResultSetSize 5000 | Select -Exp Name;
$compName
from the rest of the string in the first four attempts, so we'll use the first as an example here.$compArray += Get-ADComputer -Filter 'Name -eq "' + $compName + '*"' -SearchBase "OU=Office,DC=workplace,DC=org" -ResultSetSize 5000 | Select -Exp Name;
$compArray += Get-ADComputer -Filter *| where {$_.name -match "$compName[0-9][0-9][0-9][0-9]"} -SearchBase "OU=Office,DC=workplace,DC=org" -ResultSetSize 5000 | Select -Exp Name;
A couple of things to note with the above method, it wasn't very clear to me where $_
came from so that might be the cause of some issues. The other is that since this method uses some form of regex I thought I could search for what I'm trying to use a wildcard for which is a series of 4 digits but that didn't seem to help.
where-object
too that failed me as well.$compArray += Get-ADComputer where-object 'Name -like "*$compName*"' -SearchBase "OU=Office,DC=workplace,DC=org" -ResultSetSize 5000 | Select -Exp Name;
As I alluded to above I'm not sure why any of my attempts didn't work hence I'm asking the question here. What am I doing wrong when trying to Get-ADComputer
with a variable and a wildcard? I only need one of them to work so no one needs to figure out the issues with all of them but if you'd like to feel free.
Upvotes: 0
Views: 8049
Reputation: 10799
Instead of doing a comparison with -eq
and a wildcard, use the -like
operator. -eq
looks for an exact match, and doesn't handle wildcards; -like
does:
Get-ADComputer -Filter "Name -like '*$ComputerName*'" -SearchBase ...
Upvotes: 2