'List if AD group member is enabled or disabled in CSV file

I have following script and it works fine. I am trying to add 'Enabled' column in the end but not sure how to add it as an expanded property.

Import-Module ActiveDirectory
#create an empty array
$temp = @()

#make it multi-dimensional array
$Record = @{
  "Group Name" = ""
  "Name" = ""
  "Username" = ""
  "Enabled" = ""
}

$Groups = (Get-AdGroup -filter * -SearchBase "CN=Domain Admins,CN..." | Where {$_.name -like "**"} | select name -ExpandProperty name)

Foreach ($Group in $Groups) {

  $Arrayofmembers = Get-ADGroupMember -identity $Group -recursive | select name,samaccountname, enabled

  foreach ($Member in $Arrayofmembers) {
    
    $Record."Group Name" = $Group
    $Record."UserName" = $Member.samaccountname
    $Record."Name" = $Member.name
    $Record."Enabled" = $Member.enabled
    $objRecord = New-Object PSObject -property $Record
    $temp += $objrecord

  }
}

$temp | export-csv "C:\temp\SecurityGroups.csv" -NoTypeInformation


Solution 1:[1]

Unfortunately, the Get-ADGroupMember does not return objects with the Enabled property, so we need to use Get-ADUser for that.

BTW, it is very time and memory consuming to add items to an array with +=, because every time the entire array needs to be rebuilt in memory. It is far better to let PowerShell collect the output from the loop in an array.

Import-Module ActiveDirectory

# get an array of Group objects
$Groups = Get-AdGroup -Filter * -SearchBase "CN=Domain Admins,CN..." 

# loop through this array and capture the output in variable $result
$result = foreach ($Group in $Groups) {
    # get the members of each group.
    # members can be users, groups, and computers, so filter on users only
    $Group | Get-ADGroupMember -Recursive | Where-Object { $_.objectClass -eq 'user' } |
    ForEach-Object {
        # get the user in order to find its Enabled property
        $user = Get-ADUser -Identity $_.DistinguishedName
        [PsCustomObject]@{
            'Group Name' = $Group.Name
            'UserName'   = $user.SamAccountName
            'Name'       = $user.Name
            'Enabled'    = $user.Enabled
        }
    }
}

# now export the results to a CSV file
$result | Export-Csv "C:\temp\SecurityGroups.csv" -NoTypeInformation

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1