Expand memberOf and Display Name

Welcome Forums General PowerShell Q&A Expand memberOf and Display Name

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

 
Participant
3 months ago.

  • Author
    Posts
  • #162197

    Participant
    Topics: 1
    Replies: 0
    Points: 11
    Rank: Member

    I have a script put together to pull the memberOf AD listing for a group of users. My goal is to export these findings into a CSV that has all the groups listed out, but also still displays the SamAccountName. I don't care about removing the {CN...} and junk. My script is below:

    Import-Csv  | ForEach {
    Get-ADUser -identity $_.user -Properties SamAccountName, memberOf |
    Select SamAccountName, memberOf } | Out-File 
    

    So far, the best I've been able to find is to run:

    Select -expandproperty memberOf

    But this does not leave me with an option to display the samaccountname. Please help!

  • #162246

    Participant
    Topics: 23
    Replies: 154
    Points: 368
    Helping Hand
    Rank: Contributor

    you'll need to do some combining into a hash-table most likely here.
    without knowing your expected output, can't provide a full solution for you but, if you want an example, something like below

    Import-module ActiveDirectory  
    $path = Split-Path -parent $MyInvocation.MyCommand.Definition
    $users = import-csv users.csv
    $Results = @() 
    $output = $path + "\results.csv"
    ForEach ($item in $users)
    { 
        try
        {
            $memberships = get-adprincipalgroupmembership $item.user
            foreach ($group in $memberships)
            {
                $Properties = 
                @{
                    NetworkId = $item.user
                    Groupname = $group.name
                }
    
                $Results += New-Object psobject -Property $Properties
            }
        }
        catch
        {
            $Properties = 
            @{
                NetworkId = $item.user
                Groupname = "NOT FOUND IN DIRECTORY"
            }
            $Results += New-Object psobject -Property $Properties
        }
    }   
    $Results | export-csv $output -NoTypeInformation -append
    

The topic ‘Expand memberOf and Display Name’ is closed to new replies.