PowerShell
PowerShell copied to clipboard
Get-NestedGroup.ps1 : Line 113 : New-Object outside of foreach-loop
I believe lines 115-124 should be inside of the foreach loop bound by lines 111-113
Hey mike!
first off thanks for commenting.... so let's go through the question together....
If ($null -ne $NestedQueryResult) {
foreach ($SubGrp in $NestedQueryResult) {
$SubGrpLookup = Get-ADGroup -Identity "$($SubGrp.DistinguishedName)" -Properties Members, CanonicalName -Server $Server
}
$SubNestedGroupInfo = [PSCustomObject]@{
'ParentGroup' = $NestedADGrp.Name
'NestedGroup' = $SubGrp.Name
'NestedGroupMemberCount' = $SubGrpLookup.Members.count
'ObjectClass' = $SubGrp.ObjectClass
'ObjectPath' = $SubGrpLookup.CanonicalName
'DistinguishedName' = $SubGrpLookup.DistinguishedName
} #end PSCustomObject
$SubNestedGroupInfo
}
I am sorry the line numbers arent here, but i copied lines 110-125 ....
this IF loop is only hit if there is a nested group...
- it says IF NOT NULL then continue...
- then it says foreach group in $nestedqueryresult > do the $subgrouplookup
- then we create an pscustomobject
- then we return the object ... and then it goes back through the foreach if there are more nestedgroups in $nestedqueryresult
if I move object inside the foreach, then the next time the loop runs, it will overwrite the first result (if there are more than one).
PowerShell keeps track of the pscustomobject for me. when I come through the second time, it adds to the existing results on output. it took me a long time to understand that. but basically that's powershell stepping in and doing the work for us ...
does that make sense?
If $NestedQueryResult has 3 groups in it, this code will run the foreach loop 3 times, and $SubGrpLookup will have the value from the last object when you create the single $SubNestedGroupInfo object.
I just think it looks weird to have a foreach loop inside of the IF statement where you are throwing away all data except from the last object in $NestedQueryResult