Good Afternoon,

I am attempting to count how many objects are in 9 different OU's which is in an OU for my organizations DC. This list will specifically return only the amount of objects (computers in this situation), but the knowledge gained will help me run similar scripts on other OU's if needed.

The issue I am running into is the foreach statement does not count all items in my container, and then does not look into each different OU. Probably makes more sense if you read the script. (I have changed OU and DC names).

        Import-Module ActiveDirectory

    #IDK why we have so many DCs/A convoluted Active Directory. 
    $gci = (gci).DistinguishedName  #This selects the DistinguishedName Property of each OU (9 of them)
    $amountofOU = $gci.Count
    $amountofOU #This number is 9, because there are 9 OU's in the MACHINES OU
    $array = @()
    $i = 0 #####For counting proof that my Foreach is lazy

    foreach($item in $gci){

    $i ++  

    $DNTrim = $item.Replace($Trimthis,$null)

    $lowrgci = gci ($DNTrim).Trim()

    $amount = $lowrgci.count

    $Letter = "`nThe OU $DNTrim has $amount of objects inside" 
##This is the message I am trying to have popup at end of script, with each OU's object count in it. 
    $array += $Letter

    return $array;}
####This has been returning 1, because the foreach does not go to each $item

    #The below are just me messing around with output - 
    #Bonus points if you can make one of them work when not using console
    #(New-Object -ComObject wscript.shell).Popup("$array",2000,"OU Counter Thing",0x0 + 0x0)


I have been googling/working on this for about (sadly) 4 hours today and I have just about lost my mind. Would really appreciate any assistance; I have never had issues with a lazy Foreach statement before. My guess is I done something wrong or working in PSDRIVE AD:\ is unusual.

If you think I am lazy or that I have not done any research, I am sorry. But I feel like I have done a decent amount. Some articles I was reading:

How can I correct my foreach loop in powershell for every Active Directory OU user?


Powershell foreach statement not working


  • Read Get-Help about_return and then remove that command which breaks your foreach. – LotPings Jul 26 at 8:36
  • Such a simple fix, thanks. I feel pretty dumb for completely missing that. Whole script works now. – Perrin Talmanes Jul 26 at 18:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.