Powershell Get-ADGroupMember 不返回列表



我正在尝试利用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 组时,需要考虑的事项很少。

  1. -Identity参数只接受与对象的GuidObjectSidDistinguishedNameSamAccountName匹配的值。如果您的输入不是这些属性值之一,则需要运行另一个命令来检索正确的数据或更改列表。
  2. -Identity只接受单个值,这意味着如果要提供值列表,则需要遍历它们。
  3. Get-AdGroupMember不会输出与Get-AdUser一样多的属性/值对。您不能强制它输出比它更多的属性。它没有像Get-AdUser这样的-Properties参数。有时,它需要使用这两个命令来获取所有必需的数据。
  4. 您可以使用Export-CsvGet-Ad*输出发送到 CSV。如果不像使用Select-Object那样使用任何属性筛选,则返回的属性名称将是 CSV 的列。属性的关联值将显示在行中,每行表示一个返回的对象。您可以选择将命令的全部结果发送到 CSV 一次,或者在每次使用Export-Csv -Append运行命令时发送。
  5. 使用Select-Object仅输出您关心的属性。Select-Object Property输出一个自定义对象,该对象仅包含属性Property和返回的每个对象的Property值。如果只想返回值而不是自定义对象,可以使用Select-Object -Expand Property
  6. Get-Content可用于读取文件。如果文件仅包含值列表(可能是SamAccountName值(,则可以使用Get-Content file.txt检索该列表。该列表将是一个可以循环访问的数组。
  7. 由于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

最新更新