以下代码查询 AD 以获取有关用户帐户的信息,预计将导出一个 Excel 文件,其中包含名称、用户名、AccountEnabled(是/否)、部门、描述、LastLogonDate 以及 AD 中每个用户拥有的组。目前,该脚本按预期工作,除了在用户组下,它没有在他们都包含的任何用户上列出“域用户”。我正在尝试确定为什么以及如何解决。
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