Powershell - 从广告列表中获取用户信息

Powershell - Get User information from AD list

总的来说,我是编程初学者.. 我想要做的是创建一个 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
    }
}

到目前为止,我正在尝试让它与那一组 'Admins' 一起工作,然后如果可以的话,我想 运行 同时为更多的组编写代码。

如有任何帮助或指导,我们将不胜感激。

您似乎只需要 return 默认由 Get-ADUserGet-ADGroup 编辑的属性,因此在这两种情况下,都无需指定 [=13] =] 参数.

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

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

# 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

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