powershellactive-directoryactive-directory-group

Expanding MemberOf


Currently working on a PowerShell script for a data vault / security auditing system.

I am currently having some difficulty with the below script

$table_user = @()
$record_user = [ordered]@{
    "ObjectGUID"         = ""
    "SamAccountName"     = ""
    "Name"               = ""
    "Surname"            = ""
    "GivenName"          = ""
    "Created"            = ""
    "Modified"           = ""
    "LastLogon"          = ""
    "Enabled"            = ""
    "Office"             = ""
    "Company"            = ""
    "Department"         = ""
    "MemberOf"           = ""
    "HomeDirectory"      = ""
}
$Users = Get-AdUser -Filter * -Properties * |
         select ObjectGUID, SamAccountName, Name, Surname, GivenName,
                @{Name='Created';Expression={$_.Created.ToString("yyyy\/MM\/dd HH:mm:ss")}},
                @{Name='Modified';Expression={$_.Modified.ToString("yyyy\/MM\/dd HH:mm:ss")}},
                @{Name="LastLogon";Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp).ToString('yyyy\/MM\/dd HH:mm:ss')}},
                Enabled, Office, Company, Department, MemberOf, HomeDirectory

foreach ($user in $users) {
    $Record_User."ObjectGUID"     = $User.ObjectGUID
    $Record_User."SamAccountName" = $User.SamAccountName
    $Record_User."Name"           = $User.Name
    $Record_User."Surname"        = $User.Surname
    $Record_User."GivenName"      = $User.GivenName
    $Record_User."Created"        = $User.Created
    $Record_User."Modified"       = $User.Modified
    $Record_User."LastLogon"      = $User.LastLogon
    $Record_User."Enabled"        = $User.Enabled
    $Record_User."Office"         = $User.Office
    $Record_User."Company"        = $User.Company
    $Record_User."Department"     = $User.Department
    $Record_User."MemberOf"       = $User.MemberOf
    $Record_User."HomeDirectory"  = $User.HomeDirectory

    $objRecord = New-Object PSObject -Property $Record_User
    $table_User += $objRecord
}

I am hoping to have each row contain a unique MemberOf, e.g.;

EXAMPLE OUTPUT

Would anyone be able to assist me with how to separate the MemberOf groups so each unique group is on a separate line when exported?


Solution

  • Use a nested loop

    ForEach ($user in $users)
    {
        ForEach ($group in $user.memberOf) 
        {
            # your code to build a CSV row here
        }
    }
    

    NB. $table_User += $objRecord is ghastly slow, it does memory copies of the entire array every time you add something - so it gets slower and slower and slower. Use:

    $table_User = foreach (...) {}
    

    syntax instead, to gather the output of a foreach loop.