Reputation: 55
I have following PowerShell script
$server = Get-ADComputer -filter {name -like $computerhost}
write-host $server.name
It gives me the ADComputer that contains $computerhost
in it's name.
Example:
$computerhost = linuxserver
matching computer name output: "linuxserver01"
But I actually want the ADComputer if a name of a computer fits inside $computerhost
. So if $computerhost is "asdf" I wanna get the computer with the name "a" or "as" or "asd" or "asdf", but not "asda"
Example:
$computerhost = linuxserver (new)
matching computer name output: "linuxserver"
I have no idea how to use wildcards in that way.
Upvotes: 2
Views: 5909
Reputation: 46730
If you are looking for partial matches to your string $computerHost
filter will not handle that since it does not properly translate to a LDAP query. You would have to process that filter after returning all computers in you selection set. You parameters like -SearchScope
to reduce that if you have a large computer base. Simplest approach is to use .contains()
Get-ADComputer -filter * | Where-Object{$computerhost.contains($_.name)}
Need to be careful as .contains()
is case sensitive. One thing you could do is force both your string to the same case to remove that issue.
Where-Object{$computerhost.ToUpper().contains($_.name.toUpper())}
Can also use -match
operatore just beware that it supports regex. That should not be an issue here but if your computer names have hyphens they will need to be escaped.
Where-Object{$_.name -match $computerhost}
Upvotes: 1
Reputation: 23415
Thanks for clarifying via the comments. I think this may be what you're looking for:
Get-ADComputer -filter * | where-object { $computerhost -like "*$($_.name)*" }
For example (i'm using $computers here in place of get-adcomputer):
$computers = 'a','as','asd','asdf','asda'
$computerhost = 'asdf'
$computers | where-object { $computerhost -like "*$_*" }
Returns:
a
as
asd
asdf
Upvotes: 3