Powershell Foreach ステートメントが Get-ChildItem と組み合わせると AD で動作しない

Powershell Foreach ステートメントが Get-ChildItem と組み合わせると AD で動作しない

こんにちは、

私は、組織の DC の OU 内にある 9 つの異なる OU にいくつのオブジェクトがあるかを数えようとしています。このリストは、具体的にはオブジェクト (この状況ではコンピューター) の数だけを返しますが、得られた知識は、必要に応じて他の OU で同様のスクリプトを実行するのに役立ちます。

私が遭遇している問題は、foreach ステートメントがコンテナー内のすべての項目をカウントせず、それぞれの異なる OU を調べないことです。スクリプトを読めば、おそらくもっと理解しやすくなるでしょう。(OU 名と 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")

今日、(悲しいことに) 4 時間ほど Google で検索したり作業したりしていて、もう気が狂いそうになっています。どなたか助けていただければ幸いです。これまで、遅延 Foreach ステートメントで問題が発生したことは一度もありません。私が何か間違ったことをしたか、PSDRIVE AD:\ で作業するのが普通ではないのだと思います。

私が怠け者だとか、リサーチをしていないと思われたら申し訳ありません。でも、かなりのリサーチはしたつもりです。私が読んでいた記事には次のようなものがあります。

Active Directory OU ユーザーごとに PowerShell の foreach ループを修正するにはどうすればよいですか?

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

Powershell の foreach ステートメントが機能しない

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

関連情報