搜索 AD 组成员

Searching for AD Group Membership

我正在构建一个脚本来查找 X 天未登录且不属于特定安全组的 AD 用户。我在 OU 中有 2 个用户,其中一个在 DoNotDisable 安全组 (pileum) 中,另一个不在 (bubba) 中。

$DC = Get-ADDomainController
$OUs = Get-ADOrganizationalUnit -Filter 'Name -eq "test"'
$accounts = $null
$canNotDisable = Get-ADGroupMember -Identity DoNotDisable -Recursive | Select -ExpandProperty Name
$TimeStamp = get-date -format D
$description = "Disabled on " + $TimeStamp

foreach ($OU in $OUs) {
    # Search for User Accounts inactive for XX Days and Disable if not in DoNotDisable Security Group
    $accounts = Search-ADAccount -SearchBase $OU -AccountInactive -TimeSpan ([timespan]90d) -UsersOnly
        foreach($account in $accounts){
        If ($canNotDisable -contains $account){
        Write-Host "$account can not be disabled"
        } Else {
        Write-Host "$account can be disabled"
        }
    }
}

如果我查看 $canNotDisable 变量,它会将正确的用户拉入 DoNotDisable 组。

然而,当我 运行 完整脚本时,它 returns 组中的用户和不在组中的用户。

如果有人能帮我弄清楚我遗漏了什么,我将不胜感激。 TIA.

我认为这里的问题是Get-ADGroupMember 返回的对象与Get-ADUser 返回的对象类型不同。它们都代表 AD 用户,但对象并不相同,也许令人惊讶的是,尚未对这些类型的对象进行正确比较。

如果这是问题所在,我希望首先从 $canNotDisable 列表中获取 ObjectGUID 列表(例如 $canNotDisableGuids = $canNotDisable | %{$_.ObjectGuid}),然后检查以查看如果每个用户的 ObjectGUID 都在列表中,则可能确实有效。两个对象中的 ObjectGUID 似乎相同。

更改内部 foreach 循环中的 if 语句以匹配 ID,而不是整个对象。

由于 $canNotDisable 是一个字符串列表,您需要从 $Account 变量中获取名称以查看它是否存在(不是结果对象)。

foreach ($OU in $OUs) {
    # Search for User Accounts inactive for XX Days and Disable if not in DoNotDisable Security Group
    $accounts = Search-ADAccount -SearchBase $OU -AccountInactive -TimeSpan ([timespan]90d) -UsersOnly
        foreach($account in $accounts){
        If ($canNotDisable -contains $account.Name){
        Write-Host "$account can not be disabled"
        } Else {
        Write-Host "$account can be disabled"
        }
    }
}