我正在尝试利用PowerShell来审核AD中的所有安全组成员。 我一直在尝试让Get-ADGroupMember
工作,但每当我尝试时,它都会返回消息"找不到具有标识'groupName'的对象:"DC=xxxx,DC=xx,DC=xxxx,DC=xxxx"。
我尝试了以下方法,但没有运气:
$groupNames = 'groupName1' , 'groupName2' , 'groupName3'
foreach ($group in $groupNames) {
Get-AdGroupMember -Identity $group
}
有没有人成功地从AD编译安全组中的组成员列表并将其导出到..CSV?
使用Get-AdGroup*
命令查询 AD 组时,需要考虑的事项很少。
-Identity
参数只接受与对象的Guid
、ObjectSid
、DistinguishedName
或SamAccountName
匹配的值。如果您的输入不是这些属性值之一,则需要运行另一个命令来检索正确的数据或更改列表。-Identity
只接受单个值,这意味着如果要提供值列表,则需要遍历它们。Get-AdGroupMember
不会输出与Get-AdUser
一样多的属性/值对。您不能强制它输出比它更多的属性。它没有像Get-AdUser
这样的-Properties
参数。有时,它需要使用这两个命令来获取所有必需的数据。- 您可以使用
Export-Csv
将Get-Ad*
输出发送到 CSV。如果不像使用Select-Object
那样使用任何属性筛选,则返回的属性名称将是 CSV 的列。属性的关联值将显示在行中,每行表示一个返回的对象。您可以选择将命令的全部结果发送到 CSV 一次,或者在每次使用Export-Csv -Append
运行命令时发送。 - 使用
Select-Object
仅输出您关心的属性。Select-Object Property
输出一个自定义对象,该对象仅包含属性Property
和返回的每个对象的Property
值。如果只想返回值而不是自定义对象,可以使用Select-Object -Expand Property
。 Get-Content
可用于读取文件。如果文件仅包含值列表(可能是SamAccountName
值(,则可以使用Get-Content file.txt
检索该列表。该列表将是一个可以循环访问的数组。- 由于
Get-AdUser
可能很详细,因此明智的做法是使用-Properties
参数显式列出要返回的默认设置之外的任何额外属性。-Properties *
将返回所有属性,但这不是最佳做法。
鉴于上述考虑,我将执行以下操作:
$groupNames = 'groupName1' , 'groupName2' , 'groupName3'
# Alternatively, if you have a file (file.txt) with your group names listed as one group per line
$groupNames = Get-Content file.txt
# The Foreach-Object section is only needed if $groupNames does not contain a valid -Identity value
# The Filter below uses Name attribute as an example because it assumes $groupNames contains Name attribute values. If it contains another attribute, update the filter accordingly.
$SamAccountNames = $groupNames | Foreach-Object {
Get-AdGroup -Filter "Name -eq '$_'" | Select-Object -Expand SamAccountName
}
# Storing the loop output into a variable is efficient provided you have enough memory for the operation.
# Alternatively, you can just pipe the `Get-AdGroupMember` into `Export-Csv -Append` but that could be a lot of writes!
$output = foreach ($group in $SamAccountNames) {
Get-AdGroupMember -Identity $group # You can use Select-Object here for specific properties
}
$output | Export-Csv -Path output.csv -NoTypeInformation