powershellcsvactive-directoryadgroup

How to only select specific columns to export from an AD group through Powershell


I'm trying to get a list of group members from a single AD group and export them to a csv file. I had an issue where I was getting an error Get-ADGroupMember : The size limit for this request was exceeded since my data is over 5k. I fixed this by applying -Expand Member and using Get-ADGroup GroupName -Properties Member. The data is exported to csv, however, I only want 3 columns. At the moment I am getting all the columns that are in the group. I tried with Get-ADUser -Property name, objectClass,distinguishedName but it still outputs all the columns in the group. Is there a way to only get those 3 columns?

This is how my code looks so far:

$groupNames = @("GroupName1", "GroupName2", "GroupName3", "GroupName4")

For ($i=0; $i -lt $groupNames.Length; $i++) {
    $currentGroup = $groupNames[$i]
    $csvPath = “$currentGroup.csv”

    Get-ADGroup $groupNames[$i] -Properties Member | Select-Object -Expand Member | Get-ADUser -Property name, objectClass,distinguishedName | Export-CSV -Path $csvPath -NoTypeInformation

    }

Solution

  • You're missing a pipe to Select-Object name, objectClass, distinguishedName before outputting to Csv to filter those properties of interest. Here is a more efficient way of doing what you're up to, instead of querying each member of the groups, ask Active Directory for all users that are a memberof each group:

    $groupNames = @('GroupName1', 'GroupName2', 'GroupName3', 'GroupName4')
    
    foreach ($group in $groupNames) {
        $csvPath = "$group.csv"
        $groupdn = (Get-ADGroup $group).DistinguishedName
        Get-ADUser -LDAPFilter "(memberof=$groupdn)" |
            Select-Object name, objectClass, distinguishedName |
            Export-Csv -Path $csvPath -NoTypeInformation
    }