Pulling user groups from a list of users

Welcome Forums General PowerShell Q&A Pulling user groups from a list of users

This topic contains 1 reply, has 2 voices, and was last updated by

 
Participant
4 months, 1 week ago.

  • Author
    Posts
  • #102601

    Participant
    Points: 0
    Rank: Member

    File example(csv)

    username
    mike johnson
    steve clarke
    henry smith
    

    Code so far:

    Import-Csv C:\Users.csv | 
        ForEach-Object{
            Get-AdUser -Filter "displayname -eq '$($_.username)'" -Properties memberof
        } |
        Select-Object samaccountname, name, @{n='memberof';e={$_.memberof -join ';'}} |
        Export-Csv -Path C:\UserPermiss.csv -NoTypeInformation
    

    This pulls back the correct info, but I want just the group name, not the whole CN=, OU= etc..

    Cheers,
    Mike

  • #102622

    Participant
    Points: 19
    Rank: Member

    The simplest way to get that is just to use regex to pull the values out:

    Import-Csv -Path 'C:\Users.csv' | 
        Select-Object -ExpandProperty Username |
        Get-ADUser -Properties memberof |
        Select-Object -Property samaccountname, name, @{
            Name = 'memberof'
            Expression = {
                @($_.memberof) -match "(?< =CN\=)(.+)(?=,OU\=)" -join ';'
            }
        } | Export-Csv -Path C:\UserPermiss.csv -NoTypeInformation

    In short, that goes through the array outputting everything that appears between "CN=" and ",OU=" in each string, then joins it with ';' characters. Feel free to add spaces there or change that for another character or whatever you wanna do.

    This is one of those interesting things where the -match operator operates on arrays a bit differently vs single items, so we're ensuring it gets an array to look at.

The topic ‘Pulling user groups from a list of users’ is closed to new replies.