首页 > 解决方案 > 获取 ADPropertyValueCollection 的长度,或检查是否为空/未设置

问题描述

我正在遍历 AD 用户列表并报告他们的 proxyAddresses。我希望能够检查长度 0 或检查空/未设置。我使用 GetType 函数来确定 proxyAddresses 属性的类型为 ADPropertyValueCollection。但是查看文档(https://docs.microsoft.com/en-us/dotnet/api/microsoft.activedirectory.management.adpropertyvaluecollection-1?view=activedirectory-management-10.0)我找不到任何方法来获取长度或检查它是否为空/空。

这是我当前的代码,我只是检查它是否有内置的 PowerShell $null 变量,但是当未在用户上设置 proxyAddresses 属性时它不会捕获:

$users = Get-ADUser -Filter * -SearchBase 'DC=Domain,DC=local' -Properties "proxyAddresses"

$outputStr = ''
foreach ($user in $users) {
    if ($user.DistinguishedName -inotmatch "OU1|OU2|OU3") {
        # Skips users not in OU's we care about
        continue
    }

    if ($user.proxyAddresses -eq $null) {
        # This never fires, despite users existing with the attribute not set
        Write-Output "WARNING: User $($user.Name) found with proxyAddresses not set."
    }

    $outputStr += "Proxy addresses for $($user.Name)`r`n"
    foreach ($addr in $user.proxyAddresses) {
        $outputStr += "$($addr)`r`n"
    }
    
    $outputStr += "`r`n"
}

Out-File -FilePath 'c:\data\aliases.txt' -Encoding utf8 -InputObject $outputStr

标签: powershellactive-directory

解决方案


这很有趣,如果他们没有设置代理地址,则该属性不会与用户对象一起返回。您应该能够测试这样的代理地址的存在。

if (!$user.proxyAddresses) {
    Write-Host "WARNING: User $($user.Name) found with proxyAddresses not set."
}

推荐阅读