下午好,
我正在尝试计算我组织 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 个小时了(很遗憾),我几乎要疯了。非常感谢任何帮助;我以前从未遇到过惰性 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