使用 Get-AdUser 时如何根据 Powershell 中的多个条件过滤用户

How to filter users based on several criteria in Powershell when using Get-AdUser

我有一个问题,希望有人能帮助我。我正在尝试使用 get-adusers:

获取满足此条件的用户列表

('Sales & Admin - All'、'Field - Support'、'HKLM - All'、'SOD - 1'、'Home - 1080')中的 AD 字段“部门”以及 ('Client Manager', 'Local Sales', '外部销售, 'Region Manager', 'Deployment Manager')

中的 AD 字段“标题”

到目前为止我已经到了这一点,但不确定如何进一步。我也没有得到我部门的所有匹配项,因为它从包含数组中寻找完全匹配项:

cls
Import-Module activedirectory
$count = 0
$include_department = @("Sales & Admin - All ","Field - Support", "HKLM - All", "SOD - 1", "Home - 1080")
$include_title = @("Client Manager", "Local Sales", "Outside Sales", "Region Manager", "Deployment Manager")
$exclude_title = @("- ")
$users = Get-ADUser -filter * -properties Department, Title, SamAccountName | 
    Where-Object {
        ($_.Department -match ('(' + [string]::Join(')|(', $include_department) + ')')) -and 
        ($_.Title -match ('(' + [string]::Join(')|(', $include_title) + ')')) -and
        ($_.Department -notcontains "- ")
    }
$users | Out-File -FilePath C:\it\file.txt

Abraham pointed out in his helpful comment, you can do the filtering using exclusively the AD Filter / LDAP Filter.

这是一个 -LDAPFilter 替代方案:

$map = @{
    department = @(
        'Sales & Admin - All'
        'Field - Support'
        'HKLM - All'
        'SOD - 1'
        'Home - 1080'
    )
    title = @(
        'Client Manager'
        'Local Sales'
        'Outside Sales'
        'Region Manager'
        'Deployment Manager'
    )
}

$ldapfilter = "(&"
foreach($key in $map.Keys) {
    $clause = "(|"
    foreach($value in $map[$key]) {
        $clause += "($key=$value)"
    }
    $clause += ")"
    $ldapfilter += $clause
}
$ldapfilter += ")"

Get-ADUser -LDAPFilter $ldapfilter -Properties Department, Title, SamAccountName |
    Export-Csv path\to\export.csv -NoTypeInformation

title 过滤器是每个子句的精确匹配,因此 "摆脱/过滤器进一步列出任何其他 Titles - 在他们的名字中 应该被覆盖。

生成的 LDAP 字符串看起来像这样格式化后可读性

(&
   (|
       (department=Sales & Admin - All)
       (department=Field - Support)
       (department=HKLM - All)
       (department=SOD - 1)
       (department=Home - 1080)
    )
    (|
       (title=Client Manager)
       (title=Local Sales)
       (title=Outside Sales)
       (title=Region Manager)
       (title=Deployment Manager)
    )
)