Search code examples
powershellactive-directory

Unknown value in PowerShell Custom Object


I'm a beginner to PowerShell and Active Directory. I have grabbed below PowerShell script from the internet, intending to get all AD Users of Users type (in the Organization) and his all AD Groups he is part of. Am iterating AD users in outer loop with property "Name" as filter and his AD group in nested loop (code below).

Class CustomAdInfo 
{
    $UserName
    $Group
    $Email
}
$users_with_starting_letter = @('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')
foreach ( $node in $users_with_starting_letter )
{
 $filter = 'Name -like "' + $node + '*"'
 $customObjects = 
    foreach($user in $filter)
    {
        $adUserObj = Get-ADUser -Filter $user -properties SamAccountName,memberOf,EmailAddress -ResultPageSize 256 -SearchBase "CN=Users,DC=ab,DC=cd"
        $groups = $adUserObj.MemberOf | Get-ADgroup
        foreach($group in $groups)
        {
            New-Object -TypeName CustomAdInfo -Property @{
                UserName = $adUserObj.SamAccountName
                Group = $group
                Email = $adUserObj.EmailAddress
                
            }
        }
    }
    $customObjects | Select-Object -Property Username,group,Email | Export-Csv 'C:\Users\Members_and_Groups.csv' -Append
}

The Output (showing some samples here) I received is:

"System.Object[]","CN=group1,CN=Users,DC=ab,DC=cd","System.Object[]"
"System.Object[]","CN=group2,CN=Users,DC=ab,DC=cd","System.Object[]"

Expecting SamAccountName and EmailAddress of a AD User in column 1 and 3 respectively, but received some unknown value "System.Object[]". What am I missing?

Thank you a lot for the response!!


Solution

  • The issue with your code is due to a missing loop on $adUserObj, you're filtering for all users starting with a letter, i.e.: Name -like 'a*', a filter like this one will surely return more than a single user.

    To fix this but also to make your code more readable I'd suggest creating the filters first and then query the users.

    Class CustomAdInfo {
        $UserName
        $Group
        $Email
    }
    
    [char[]] ([char] 'a'..[char] 'z') | ForEach-Object {
        $getADUserSplat = @{
            Filter         = "Name -like '$_*'"
            Properties     = 'SamAccountName', 'memberOf', 'EmailAddress'
            ResultPageSize = 256
            SearchBase     = 'CN=Users,DC=ab,DC=cd'
        }
        foreach ($user in Get-ADUser @getADUserSplat) {
            foreach ($group in $user.MemberOf | Get-ADGroup) {
                [CustomAdInfo]@{
                    UserName = $user.SamAccountName
                    Group    = $group.Name # <= You need to choose an attribute here
                    Email    = $user.EmailAddress
                }
            }
        }
    } | Export-Csv 'C:\Users\Members_and_Groups.csv'