Search code examples
powershellpowershell-5.0active-directory-group

Searching for AD Group Membership


I am building a script to find AD Users that have not logged in X number of days and do not belong to a specific security group. I have 2 users in the OU, one of which is in the DoNotDisable security group (pileum) and one which is not (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"
        }
    }
}

If I look at the $canNotDisable variable it is pulling the correct user in the DoNotDisable group.

enter image description here

However when I run the full script it returns both the user in the group and the user not in the group.

enter image description here

I would be extremely grateful if someone can help me figure out what I'm missing. TIA.


Solution

  • Change your if statement in inner foreach loop to match against the IDs, not the whole object.

    Since $canNotDisable is a list of strings, you will need to get the name out of the $Account variable to see if that exists (not the resulting object).

    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"
            }
        }
    }