You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PowerShell遍历AD组数组获取成员时结果异常且报错

问题场景

需要获取属于Group1、Group2、Group3、Group4中至少一个组的禁用AD用户,执行以下命令时出现管道绑定错误:

循环组的命令

$groups = @('Group1','Group2','Group3','Group4')

foreach ($i in $groups)  {Get-ADGroupMember $i | Get-ADUser -Filter * -Properties * | Where-Object {$_.Enabled -eq $False} | Select CN }

单个组的命令

Get-ADGroupMember 'Group1' | Get-ADUser -Filter * -Properties * | Where-Object {$_.Enabled -eq $False} | Select CN

错误信息(翻译后)

Get-ADUser : 输入对象无法绑定到该命令的任何参数,原因是该命令不接受管道输入,或者输入及其属性与任何接受管道输入的参数都不匹配。
At line:1 char:50
CategoryInfo: InvalidArgument: (REDACTED) [Get-ADUser], ParameterBindingException
FullyQualifiedErrorId: InputObjectNotBound,Microsoft.ActiveDirectory.Management.Commands.GetADUser
问题原因
  1. Get-ADGroupMember返回的对象不仅包含用户,还可能包含嵌套的AD组对象。Get-ADUser只能处理用户对象,当组对象进入管道时,就会触发参数绑定错误。
  2. 给Get-ADUser添加-Filter *属于冗余操作,管道传递用户对象时,该命令会自动识别对象,无需额外过滤。
解决方案

方案1:过滤组成员中的用户对象

先从Get-ADGroupMember的结果里筛选出类型为用户的对象,再传给Get-ADUser;如果需要包含嵌套组的用户,加上-Recursive参数:

$groups = @('Group1','Group2','Group3','Group4')

foreach ($group in $groups) {
    Get-ADGroupMember -Identity $group -Recursive | 
        Where-Object {$_.objectClass -eq 'user'} |
        Get-ADUser -Properties Enabled |
        Where-Object {$_.Enabled -eq $false} |
        Select-Object CN
}

注:无需使用-Properties *,仅加载需要的Enabled属性可提升执行效率。

方案2:直接查询符合条件的AD用户(更高效)

跳过Get-ADGroupMember,直接用Get-ADUser查询属于目标组且禁用的用户,避免管道传递对象的问题:

$groups = @('Group1','Group2','Group3','Group4')
$groupFilters = $groups | ForEach-Object { "memberOf -eq '$($_)'" }
$combinedFilter = $groupFilters -join ' -or '

Get-ADUser -Filter $combinedFilter -Properties Enabled |
    Where-Object {$_.Enabled -eq $false} |
    Select-Object CN

内容的提问来源于stack exchange,提问作者Ryan Dechant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 17:24:58