The following code query's AD for information on user accounts and is expected to export an excel file that contains the Name, Username, AccountEnabled(yes/no), Department, Description, LastLogonDate, and what groups every user in AD has. Currently the script works as intended except that under the users Groups, it does not list 'Domain User' on ANY user which they all contain. I am trying to determine why and how to fix.
Import-Module ActiveDirectory
$Report = @()
#Collect all users
$Users = Get-ADUser -Filter * -Properties Name, GivenName, SurName, SamAccountName, UserPrincipalName, MemberOf, Enabled, Department, Description, LastLogonDate -ResultSetSize $Null
# Use ForEach loop, as we need group membership for every account that is collected.
# MemberOf property of User object has the list of groups and is available in DN format.
Foreach($User in $Users){
$UserGroupCollection = $User.MemberOf
#This Array will hold Group Names to which the user belongs.
$UserGroupMembership = @()
#To get the Group Names from DN format we will again use Foreach loop to query every DN and retrieve the Name property of Group.
Foreach($UserGroup in $UserGroupCollection){
$GroupDetails = Get-ADGroup -Identity $UserGroup
#Here we will add each group Name to UserGroupMembership array
$UserGroupMembership += $GroupDetails.Name
}
#As the UserGroupMembership is array we need to join element with ‘,’ as the seperator
$Groups = $UserGroupMembership -join ‘, ‘
#Creating custom objects
$Out = New-Object PSObject
$Out | Add-Member -MemberType noteproperty -Name Name -Value $User.Name
$Out | Add-Member -MemberType noteproperty -Name UserName -Value $User.SamAccountName
$Out | Add-Member -MemberType noteproperty -Name Enabled -Value $User.Enabled
$Out | Add-Member -MemberType noteproperty -Name Department -Value $User.Department
$Out | Add-Member -MemberType noteproperty -Name Description -Value $User.Description
$Out | Add-Member -MemberType noteproperty -Name LastLogonDate -Value $User.LastLogonDate
$Out | Add-Member -MemberType noteproperty -Name Groups -Value $Groups
$Report += $Out
}
#Output to screen as well as csv file.
#$Report | Sort-Object Name | FT -AutoSize
$Report | Sort-Object Name | Export-Csv -Path "C:\Scripts\Output\users.csv" -NoTypeInformation -Encoding UTF8
You are not seeing it because it's the primary group for most users. See this question for a better explanation. https://serverfault.com/questions/955721/why-is-the-domain-users-group-missing-from-this-powershell-ad-query
As for your script it can probably be simplified a bit by using pipes and calculated properties.
And if you want it to run faster remove the Get-AdGroup command and replace it with a split/trim command. Although that is a bit more janky, but a lot faster.
A more elegant way of creating a custom object like you are doing would be something like this.