
午安,
我正在嘗試計算 9 個不同的 OU 中有多少對象,這些對象位於我的組織 DC 的 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")
今天我已經在谷歌上搜尋/研究這個問題大約(可悲的是)四個小時,我幾乎失去了理智。非常感謝任何幫助;我以前從未遇到過惰性 Foreach 語句的問題。我的猜測是我做錯了什麼或在 PSDRIVE AD:\ 中工作是不尋常的。
如果你認為我很懶或我沒有做過任何研究,我很抱歉。但我覺得我已經做了相當多的事情了。我正在閱讀的一些文章:
如何為每個 Active Directory OU 使用者修正 powershell 中的 foreach 迴圈?
https://powershell.org/forums/topic/foreach-loop-not-working/
https://serverfault.com/search?q=Active+directory+get+child+item