首页 > 解决方案 > 获取 AD-Computer 不像专有名称

问题描述

我正在尝试从 AD 获取计算机列表,不包括一些不再使用的计算机。这是我的代码:

$ServerList = Get-ADComputer -Filter * | Where { 
    $_.DistinguishedName -like "*Computers*" -and $_.DistinguishedName -notlike @("*server1*","*Server2*")
} | Select-Object Name 

我正在尝试将要排除的计算机放入数组中,而不是使用

-and $_.DistinguishedName -notlike "*serverIwantToExclude*"

你们能告诉我如何修改它吗?

标签: windowspowershellactive-directory

解决方案


-notlike不支持右侧的集合 (RHS)。一个类似的方法是使用-notmatch,它是一个正则表达式字符串:

$ServerList = Get-ADComputer -Filter * |
    Where { $_.DistinguishedName -like "*Computers*" -and $_.DistinguishedName -notmatch 'server1|Server2'} |
        Select-Object Name

如果您希望您的服务器名称首先出现在列表中,您可以从中创建一个正则表达式字符串。

$serverdown = 'server1','server2'
$regex = $serverdown -join '|'
$ServerList = Get-ADComputer -Filter * |
    Where { $_.DistinguishedName -like "*Computers*" -and $_.DistinguishedName -notmatch $regex} |
        Select-Object Name

如果您不锚定您的正则表达式字符串,它会在目标字符串中的任何位置查找正则表达式匹配项(实际上具有周围的通配符)。|是一个交替(一个有效的OR)。

还有其他支持集合的运算符,如-contains, -in,-notin-notcontains. 但是,它们必须完全匹配并且不能使用通配符。


推荐阅读