如何使用 Get-ADComputer 过滤器获取所有部分匹配项?
How can I get all partial matches using Get-ADComputer filter?
我有以下 PowerShell 脚本
$server = Get-ADComputer -filter {name -like $computerhost}
write-host $server.name
它给了我名称中包含 $computerhost
的 ADComputer。
示例:
$computerhost = linuxserver
匹配的计算机名称输出:"linuxserver01"
但如果计算机名称适合 $computerhost
,我实际上想要 ADComputer。因此,如果 $computerhost 是 "asdf",我想获得名称为 "a" 或 "as" 或 "asd" 或 "asdf" 的计算机,但不是 "asda"
示例:
$computerhost = linuxserver (new)
匹配的计算机名称输出:"linuxserver"
我不知道如何以这种方式使用通配符。
感谢您通过评论进行澄清。我想这可能是您要找的:
Get-ADComputer -filter * | where-object { $computerhost -like "*$($_.name)*" }
例如(我在这里使用 $computers 代替 get-adcomputer):
$computers = 'a','as','asd','asdf','asda'
$computerhost = 'asdf'
$computers | where-object { $computerhost -like "*$_*" }
Returns:
a
as
asd
asdf
如果您要查找与您的字符串部分匹配的内容,$computerHost
过滤器将不会处理该问题,因为它无法正确转换为 LDAP 查询。在返回选择集中的所有计算机后,您必须处理该过滤器。如果你有一个庞大的计算机基础,你可以像 -SearchScope
这样的参数来减少它。最简单的方法是使用 .contains()
Get-ADComputer -filter * | Where-Object{$computerhost.contains($_.name)}
需要小心,因为 .contains()
区分大小写。您可以做的一件事是将两个字符串都强制为相同的大小写以消除该问题。
Where-Object{$computerhost.ToUpper().contains($_.name.toUpper())}
也可以使用 -match
运算符,只是要注意它支持正则表达式。这在这里应该不是问题,但如果您的计算机名称有连字符,则需要对其进行转义。
Where-Object{$_.name -match $computerhost}
我有以下 PowerShell 脚本
$server = Get-ADComputer -filter {name -like $computerhost}
write-host $server.name
它给了我名称中包含 $computerhost
的 ADComputer。
示例:
$computerhost = linuxserver
匹配的计算机名称输出:"linuxserver01"
但如果计算机名称适合 $computerhost
,我实际上想要 ADComputer。因此,如果 $computerhost 是 "asdf",我想获得名称为 "a" 或 "as" 或 "asd" 或 "asdf" 的计算机,但不是 "asda"
示例:
$computerhost = linuxserver (new)
匹配的计算机名称输出:"linuxserver"
我不知道如何以这种方式使用通配符。
感谢您通过评论进行澄清。我想这可能是您要找的:
Get-ADComputer -filter * | where-object { $computerhost -like "*$($_.name)*" }
例如(我在这里使用 $computers 代替 get-adcomputer):
$computers = 'a','as','asd','asdf','asda'
$computerhost = 'asdf'
$computers | where-object { $computerhost -like "*$_*" }
Returns:
a
as
asd
asdf
如果您要查找与您的字符串部分匹配的内容,$computerHost
过滤器将不会处理该问题,因为它无法正确转换为 LDAP 查询。在返回选择集中的所有计算机后,您必须处理该过滤器。如果你有一个庞大的计算机基础,你可以像 -SearchScope
这样的参数来减少它。最简单的方法是使用 .contains()
Get-ADComputer -filter * | Where-Object{$computerhost.contains($_.name)}
需要小心,因为 .contains()
区分大小写。您可以做的一件事是将两个字符串都强制为相同的大小写以消除该问题。
Where-Object{$computerhost.ToUpper().contains($_.name.toUpper())}
也可以使用 -match
运算符,只是要注意它支持正则表达式。这在这里应该不是问题,但如果您的计算机名称有连字符,则需要对其进行转义。
Where-Object{$_.name -match $computerhost}