首页 > 解决方案 > Powershell - 从 AD 列表中获取用户信息

问题描述

我是一般编程的初学者。我想做的是创建一个powershell脚本,它将:

这是我到目前为止所拥有的:

$list = Get-ADGroupMember Admins

foreach($u in $list) {
    Get-ADObject $u
}

foreach ($_ in $u) {
    if ($u.ObjectClass -eq 'user') { 
        Get-ADUser $u -Properties * | select givenname, surname, samaccountname | ft -autosize
    } else { 
        Get-ADGroupMember $u -Recursive | select name, samaccountname | ft -autosize
    }
}

到目前为止,我正试图让它与那一组“管理员”一起工作,然后如果是这样,我想同时为更多组运行代码。

任何帮助或指导将不胜感激。

标签: powershellactive-directoryusergroups

解决方案


您似乎只需要默认返回的属性Get-ADUser以及Get-ADGroup,因此在这两种情况下,都不需要指定-Properties参数。

Get-ADGroupMember可以返回用户、计算机和组对象,因此目前,您的else条件需要组,您最终可能会得到一个计算机对象。

ft -autosize在您的代码中,您使用inif和 the输出到控制台else,但是在循环开始时在变量中捕获这两种类型的结果对象并在之后将其作为一个整体输出会更简单:

# you can load a list of group names from a predefined array:
$Groups = 'Admins', 'Users'

# or load from a file, each group name listed on a separate line:
# $Groups = Get-Content -Path 'D:\Test\ADGroups.txt'

# or get all AD groups in the domain:
# $Groups = (Get-ADGroup -Filter *).Name


$result = foreach ($group in $Groups) {
    Get-ADGroup -Filter "Name -eq '$group'" | ForEach-Object {
        # we could use the $group variable, but this ensures correct casing
        $groupName = $_.Name
        $members = $_ | Get-ADGroupMember -Recursive
        foreach ($member in $members) {
            if ($member.objectClass -eq 'user') {
                Get-ADUser -Identity $member.DistinguishedName |
                Select-Object @{Name="GroupName"; Expression={$groupName}},
                              @{Name="MemberType";Expression={'User'}},
                              Name, 
                              GivenName, 
                              Surname, 
                              SamAccountName
            }
            elseif ($member.objectClass -eq 'group') {
                Get-ADGroup -Identity $member.DistinguishedName |
                Select-Object @{Name="GroupName";Expression={$groupName}},
                              @{Name="MemberType";Expression={'Group'}},
                              Name,
                              @{Name="GivenName";Expression={''}},  # groups don't have this property
                              @{Name="Surname";Expression={''}},    # groups don't have this property
                              SamAccountName
            }
        }
    }
}

# output is console
$result | Format-Table -AutoSize

# write to CSV file
$result | Export-Csv -Path 'D:\Test\GroupsInfo.csv' -NoTypeInformation

诀窍是为用户和组对象输出具有相同属性的对象


推荐阅读