powershell - Powershell - 从 AD 列表中获取用户信息
问题描述
我是一般编程的初学者。我想做的是创建一个powershell脚本,它将:
获取有关 Active Directory 组中每个用户的信息。
每个组内可能还有另一个组,所以我希望它也能从每个嵌套组中获取用户列表。
只给我每个组的信息一次。
这是我到目前为止所拥有的:
$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
}
}
到目前为止,我正试图让它与那一组“管理员”一起工作,然后如果是这样,我想同时为更多组运行代码。
任何帮助或指导将不胜感激。
解决方案
您似乎只需要默认返回的属性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
诀窍是为用户和组对象输出具有相同属性的对象
推荐阅读
- firebase - 使用 react native 应用程序连接和测试 firebase 模拟器的正确方法
- postgresql - PostgreSQL 在日期 2021-01-01 的一周内返回错误的 date_part
- html - 如何添加带有内容的新行以形成
- sql - 从 bacth 文件调用 SQL 脚本时的额外输出行
- node.js - 如何在猫鼬中将 this.getQuery() 替换为 this.getFilter()
- python - 获取图像中像素的十六进制颜色代码和坐标
- aws-lambda - 如何在 lambda 函数中安装操作系统级别的依赖项
- c++ - 如果提供了 + '0',如何将整数附加到字符串
- java - 在 Java 中创建具有类作为数据类型的对象
- javascript - Postgresql 在向邮递员发出请求时要求输入密码