求助:PowerShell脚本无法读取并显示AD嵌套通讯组
问题
我花了两天时间尝试用PowerShell脚本在控制台显示AD通讯组中的嵌套通讯组名称,但始终失败。已知名为XXX的AD通讯组包含2个邮件联系人和2个嵌套通讯组,我需要快速验证结果,让脚本读取该组并提取显示所有嵌套通讯组名称。当前使用的脚本如下:
$UserCredential = Get-Credential $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://ABC.DEF.com/PowerShell/ -Authentication Kerberos -Credential $UserCredential Import-PSSession $Session -DisableNameChecking Import-Module Activedirectory $groupName = 'XXX' $groupMembers = Get-DistributionGroupMember -Identity $groupName -ResultSize Unlimited $nestedGroups = $groupMembers | Where-Object { $_.RecipientTypeDetails -eq 'MailUniversalDistributionGroup' } $nestedGroups | ForEach-Object { Write-Output "Nested Group: $($_.DisplayName)" }
排查与解决
检查嵌套组的实际类型
你的脚本只过滤了MailUniversalDistributionGroup类型,但嵌套组可能是其他通讯组/安全组类型。先执行以下命令查看所有成员的类型:$groupMembers | Select-Object DisplayName, RecipientTypeDetails修正过滤条件
根据上面的结果,调整Where-Object的过滤逻辑,覆盖所有可能的组类型:$nestedGroups = $groupMembers | Where-Object { $_.RecipientTypeDetails -in 'MailUniversalDistributionGroup', 'MailNonUniversalDistributionGroup', 'MailUniversalSecurityGroup', 'MailNonUniversalSecurityGroup' }如果需要递归获取所有嵌套组
若目标组的嵌套层级不止一层,Get-DistributionGroupMember无法直接递归,需使用递归函数:function Get-NestedGroups { param([string]$GroupIdentity) $members = Get-DistributionGroupMember -Identity $GroupIdentity -ResultSize Unlimited foreach ($member in $members) { if ($member.RecipientTypeDetails -match 'DistributionGroup|SecurityGroup') { $member # 递归调用获取子组的成员 Get-NestedGroups -GroupIdentity $member.Identity } } } # 获取所有嵌套组并输出 $allNestedGroups = Get-NestedGroups -GroupIdentity $groupName $allNestedGroups | Select-Object DisplayName, RecipientTypeDetails | Format-Table -AutoSize验证Exchange会话有效性
确认Import-PSSession成功加载Exchange命令,执行以下命令检查:Get-Command Get-DistributionGroupMember
内容的提问来源于stack exchange,提问作者user270488
相关产品推荐
相关产品推荐

