在使用Get-AdUser时如何根据PowerShell中的几个条件过滤用户

xtupzzrd  于 2022-11-10  发布在  Shell
关注(0)|答案(1)|浏览(154)

我有一个问题,我希望有人能帮我。我正在尝试使用Get-aduser获取符合此标准的用户列表:
(‘Sales&Admin-All’,‘field-Support’,‘HKLM-All’,‘SOD-1’,‘Home-1080’)中的广告字段“Department”和(‘Client Manager’,‘Local Sales’,‘Outside Sales,’Region Manager‘,’Deploy Manager‘)中的广告字段“标题”

  • “标题”可以在用“-”分隔后附加另一个值,即“客户协调员-咨询/解决方案”。我还需要进一步删除/过滤该列表中名称中包含“-”的任何其他书目。

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

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
ee7vknir

ee7vknir1#

正如Abraham在他有用的评论中指出的那样,您可以只使用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)
    )
)

相关问题