尝试从 AD 中提取包含我所有用户的列表,一个名为 Disabled Users 的 OU 除外。如何从我的列表中排除此 OU?

Trying to extract a list from AD that contains all of my users, in exception to one OU named Disabled Users. How can I exclude this OU from my list?

这是我目前拥有的:

Get-ADUser -Filter 'Department -like "*"' -Properties * |
    Select -Property DisplayName,GivenName,Surname,Title,Department,Office,OfficePhone |
    Export-CSV "C:\ad-users.csv"

我相信你可以使用 -LDAPFilter 这样做,首先你需要查询要排除的 OU 并得到它 DistinguishedName 然后你可以查询所有用户并在他们的 DistinguishedName 不包含要排除的 OU。

注意: 这假设 只有 1 个 OU 名称为 Disabled Users。如果有更多相同的 OU,我建议您 硬编码 $ouDN 中排除的 OU 的 DistinguishedName

同样值得注意的是,为所有用户查询所有属性-Properties *)是非常低效的,你应该总是仅查询感兴趣的属性 (-Properties attrib1, attrib2, etc).

$properties = @(
    'DisplayName'
    'GivenName'
    'Surname'
    'Title'
    'Department'
    'Office'
    'OfficePhone'
)
$ouToExclude = 'Disabled Users'
$ouDN = (Get-ADOrganizationalUnit -LDAPFilter "(Name=$ouToExclude)").DistinguishedName
Get-ADUser -LDAPFilter "(Department=*)" -Properties $properties | & {
    process {
        if($_.DistinguishedName -notlike "*$ouDN") { $_ }
    }
} | Select-Object $properties | Export-Csv "C:\ad-users.csv" -NoTypeInformation

您可以使用 Where-Object 子句来过滤用户 OU

# fill in the DistinguishedName of the 'Disabled Users' OU here
$ouToExclude = 'OU=...'

# Get-ADUser by default returns these properties:
# DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName
# so you only need to ask for extra properties not already in this list
Get-ADUser -Filter "Department -like '*'" -Properties DisplayName,Title,Department,Office,OfficePhone |
Where-Object { $_.DistinguishedName -notlike "*$ouToExclude" } | 
Select-Object DisplayName,GivenName,Surname,Title,Department,Office,OfficePhone |  
Export-Csv "C:\ad-users.csv" -NoTypeInformation