-1

I'm working on AD nested groups and need some help.

Here's the code:

function Extract-Users($group, $array) {
    $members = Get-ADGroupMember -Identity $group.Name
    foreach ($member in $members) {
        if ($member.objectClass -eq "user") {
            $Admin = New-Object PSObject
            $Admin | Add-Member -Type NoteProperty -Name User -Value $user.Name
            $Admin | Add-Member -Type NoteProperty -Name Group -Value $group.Name
            $array += $Admin
            Remove-Variable Admin
            return $array
        } elseif ($member.objectClass -eq "group"){
            Extract-Users $member, $object
        }
    }
}

The issue is that I want to be able to call the function like this:

$ADGroups = Get-ADGroup -Filter {Name -like "*admin*"}
$Admins = @()
foreach ($group in $ADGroups) {
    Extract-Users $group $Admins
}

And store all the objects that are created in the function into the variable that I'm tossing into the function. So that all the users that I extract are stored into the $Admins array. I know I can write it all manual, but I want to know if there is a dynamic way of doing it.


Thanks guys

Alex
  • 498
  • 2
  • 8

1 Answers1

2

I don't believe it is possible to use dynamic function stored in a variable per say but I believe you could achieve the desired result using a byref parameters.

Simple example

$Users = @()

function Extract-Users{
Param([Parameter(Mandatory=$true)]$group,
  [Parameter(Mandatory=$true)][ref]$array)

$array.Value += (Get-Random)
return $array.Value.count 
}

That way, the Extract-Users $array parameter is used and operations performed by the function are added to the existing array passed down.

You can use the return value for whatever other purposes or ignore it entirely.

Simple demonstration

Here, my extract-users actually use the $array parameter and add a random number to it. You could, however, add users instead.

cls

$group = 'something'
Write-host 'Users count:' (Extract-Users $group  ([ref]$Users))

Write-Host '$Users variable content'
$Users | ft 


Write-host 'Users count:' (Extract-Users $group  ([ref]$Users))
Write-host 'Users count:' (Extract-Users $group  ([ref]$Users))
Write-host 'Users count:' (Extract-Users $group  ([ref]$Users))

Write-Host ([Environment]::NewLine)
Write-Host 'Here is the $Users variable content'
$Users | ft

The important point to note are that you need to pass the parameter that way ([ref]$MyParam) instead of just $MyParam and also in the function, you want to update the .value property and not the variable itself.

Edit: Well, as Rohin point out in the OP questions, a deceptively simple

$FinalArray += Extract-Users $group $Admins

do the trick perfectly well.

If you need the return value to be different (for instance to get a boolean result success/false status or get the count of users or anything else, the [ref] will be perfect for t

Sage Pourpre
  • 9,932
  • 3
  • 27
  • 39