2023 Jan 8

Get a List of Enabled Users in Group(s)

In case you have an audit, and being asked to provide all the members of the group(s), and have a very specific pattern (like ending with "RW" as a random example), and you are not removing the users from the groups when they leave the company (anything if not everything is possible), you can use the following function (as it is, or add it to your $profile).

To do the above, all we need to do is to create a function that accepts the mandatory parameter to match with our need. The line 8 check for active users only, you can remove it if you like. Also, you can add Export-CSV with the file you like, also it accepts the pipeline input, that means, you can provide a set of strings separated by comma before the pipeline and add the function with no parameters in the end, for example:

"Group 1", "RW", "Domain" | Get-EnabledADGroupMember

You can also change the Get-ADGroupmember with something like (Get-ADGroup $Group -properties member).member in case you get the unspecified error, but it doesn't support a recursive search.

Here is the script. You don't need to specify the domain unless you have a domain trust with someone else's, and want to limit the results for this or another reason:

function Get-EnabledADGroupMember {
    process {
    $groups=(Get-ADGroup -filter "name -like '*$ADGroup*'"  | sort name).name
        foreach ($group in $groups) {
            $Members = Get-ADGroupMember $Group -recursive | Get-ADUser -Server contoso.com -ErrorAction Ignore | Sort-Object samaccountname | ?{$_.enabled -eq $True}
            foreach ($Member in $Members) {
                    "Group" = $Group
                    "Name" = $Member.Name
                    "SamAccountName" = $Member.samaccountname
                    "Enabled" = $Member.enabled

Let's break it down and explain some lines from above.
Firstly, we specify the function name, and the input parameter. We have just one, so it's easy. Also, it will be mandatory, so you will be asked to enter something even if you just type the function. The ValueFromPipeline is explained a bit above. It basically allows you to specify more inputs at the same time, which might be useful in some complex cases.
In the process section, we specify a set of groups that match the pattern. It takes the name, and puts everything after and before the string, so if you select "RW", it will match "Photos_RW", "SRWork" and "RWorkers", so if you really want it to end or start with it, please update the filter.
We also want to ignore the warnings and proceed with just a list of groups. After all, we create a custom PS object, which is basically a table, and put what we need there. And as far as you check for enabled users only, you might not need the part with that column after all (Line 17)

They posted on the same topic

Trackback URL : https://dykhl.in/trackback/12

This post's comments feed