La declaración Powershell Foreach no funciona en AD cuando se combina con Get-ChildItem

La declaración Powershell Foreach no funciona en AD cuando se combina con Get-ChildItem

Buenas tardes,

Estoy intentando contar cuántos objetos hay en 9 unidades organizativas diferentes que se encuentran en una unidad organizativa para el DC de mi organización. Esta lista devolverá específicamente solo la cantidad de objetos (computadoras en esta situación), pero el conocimiento adquirido me ayudará a ejecutar scripts similares en otras unidades organizativas si es necesario.

El problema con el que me encuentro es que la declaración foreach no cuenta todos los elementos de mi contenedor y luego no examina cada unidad organizativa diferente. Probablemente tenga más sentido si lees el guión. (He cambiado los nombres de OU y DC).

        Import-Module ActiveDirectory

    Set-Location "AD:\OU=MACHINES,OU=WESTWING,OU=BLDG202,DC=NORTH,DC=APPS,DC=WEST,DC=HQ"
    #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
    $Trimthis = ",OU=MACHINES,OU=WESTWING,OU=BLDG202,DC=NORTH,DC=APPS,DC=WEST,DC=HQ"
    $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;}
    $i       
####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)

    [System.Windows.Forms.MessageBox]::Show("$array","Title")

He estado buscando en Google/trabajando en esto durante aproximadamente (lamentablemente) 4 horas hoy y casi me he vuelto loco. Realmente agradecería cualquier ayuda; Nunca antes había tenido problemas con una declaración Foreach perezosa. Supongo que hice algo mal o que trabajar en PSDRIVE AD:\ es inusual.

Si crees que soy un vago o que no he investigado nada, lo siento. Pero siento que he hecho bastante. Algunos artículos que estaba leyendo:

¿Cómo puedo corregir mi bucle foreach en powershell para cada usuario de unidad organizativa de Active Directory?

https://powershell.org/forums/topic/foreach-loop-not-working/

La declaración foreach de Powershell no funciona

https://serverfault.com/search?q=Active+directory+get+child+item

información relacionada