Pulling user groups from a list of users

This topic contains 1 reply, has 2 voices, and was last updated by  Joel Sallow 1 month ago.

  • Author
  • #102601


    File example(csv)

    mike johnson
    steve clarke
    henry smith

    Code so far:

    Import-Csv C:\Users.csv | 
            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..


  • #102622

    Joel Sallow

    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.

You must be logged in to reply to this topic.