1

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

5
  • None of your output lines are exact duplicates, so I don't understand why you think your code is running twice. Can you elaborate? Commented Feb 19, 2020 at 15:25
  • @Matthew Please see the output screenshot. Each computer account is listed twice instead of once except for the last 2. Commented Feb 19, 2020 at 15:33
  • @poisedforlight I would try loading the script in PowerShell ISE and stepping through the code one line at a time. This will certainly show you what your code is doing and why. Commented Feb 19, 2020 at 15:37
  • 2
    Add -SearchScope OneLevel to the Search-ADAccount command Commented Feb 19, 2020 at 16:00
  • @MathiasR.Jessen: Thank you, that worked. Commented Feb 19, 2020 at 16:05

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Your explanation is very much appreciated. That got me what I needed and more importantly I now understand why it wasn't working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.