poisedforflight
poisedforflight

Reputation: 167

ForEach Loop Iterates Twice Instead Of Once - Powershell

Once again I have broken a foreach loop and cannot figure out why. It appears to iterate twice instead of once for some of the accounts. I think I have my {} in the correct format but apparently not. Can anyone help me find what I'm missing?

Relevant Code:

foreach ($OU in $OUs) {

    # Search for User and/or Computer Objects inactive for XX days.  Disable object if not in DoNotDisable Security Groups
    $days = $days + "D"
    $accounts = Search-ADAccount -SearchBase $OU.DistinguishedName -AccountInactive -TimeSpan ([timespan]7D) @scope
    foreach($account in $accounts){
        If ($noDisable -notcontains $account.Name) {
            Write-Host $account
    #        #Disable-ADAccount -Identity $account.DistinguishedName -Verbose $whatIf | Export-Csv $logFile
       }
    }
}

Output: Each computer account is listed twice except the last 2.

enter image description here

Upvotes: 1

Views: 681

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175085

If your directory tree looks like this:

NC root
 |- TopLevelOU
     |- SubOU
     |   |- Computer1
     |   |- Computer2
     |- Computer3
     |- Computer4

... and you start by querying for all OUs, and then search (recursively) through each one, you're going to get every object under SubOU twice - once from searching through the TopLevelOU, and once more from searching directly against SubOU.

Add -SearchScope OneLevel to your Search-ADAccount invocation if you want to contain each search to the immediate children of the target OU:

$accounts = Search-ADAccount -SearchBase $OU.DistinguishedName -SearchScope OneLevel -AccountInactive -TimeSpan ([timespan]7D) @scope

Upvotes: 3

Related Questions