I had an Active Directory group containing thousands of user accounts. Each of these user accounts were a member of another group that always was just a bunch of numbers. I needed to output each group member's name, the all-number group(s) the originating group member was in and the description of that group. I then needed to put this into a CSV and the below one-liner is what emerged.

IMO, ugly and could be improved upon but the kind of script that was built-in the moment to get an immediate need fulfilled.

Get-ADGroupMember 'GROUPNAME' | foreach {
    $hash = @{}
    $hash.UserName = $_.Name
    (Get-ADUser $_.samaccountName -Properties memberof).memberof | where { $_.Split(',')[0].Trim('CN=') -match '^\d*$' } | foreach {
        $group = get-adgroup $_ -Properties description | select samaccountname,description
        $hash.GroupName = $group.samaccountname
        $hash.GroupDescription = $group.Description
        [pscustomobject]$hash
    }
} | Export-CSV -Append -NoTypeInformation -Path output.csv

Join the Jar Tippers on Patreon

It takes a lot of time to write detailed blog posts like this one. In a single-income family, this blog is one way I depend on to keep the lights on. I'd be eternally grateful if you could become a Patreon patron today!

Become a Patron!