2023 Jan 8
Get a List of Enabled Users in Group(s)
12:03 - By Andrii Dykhlin - ActiveDirectory - Permalink
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 {
[CmdletBinding()]
param(
[Parameter(Mandatory,ValueFromPipeline)]
[string]$ADGroup
)
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) {
[PSCustomObject]@{
"Group" = $Group
"Name" = $Member.Name
"SamAccountName" = $Member.samaccountname
"Enabled" = $Member.enabled
}
}
}
}
}