获取多个组的 Get-AdGroupMember

获取多个组的 Get-AdGroupMember

我如何检查提到的安全组是否存在?我还希望导出的 .csv 中显示“无成员”,而不是跳过它。

另外,我该如何完善下面的脚本?我想获取会员的详细信息。

$group_list = get-content C:\temp\group_list.txt

$results = foreach($group in $group_list){

$checkgroup = get-adgroup -filter {name -eq $group} | select name

if($checkgroup -ne $null){
                    
    $members = get-adgroupmember $group | select samaccountname
    
    if($members -ne $null){
    [PSCustomObject]@{GroupName=$group;Members=($members.samaccountname | Out-String).Trim()}
    }
    else{
    [PSCustomObject]@{GroupName=$group;Members="None"}
    }    
}
else{
    [PSCustomObject]@{GroupName=$group;Members="Group not exist"}
}
}

$results | Export-csv C:\temp\Group_Members.csv -NoTypeInformation

答案1

# output active directory groups and members to csv (also output empty groups with 'No Members' value)
# assumes run on domain controller or import of ActiveDirectory module

$allgroups = Get-ADGroup -Filter *

$result = foreach ( $group in $allgroups ) {

    $hash = @{GroupName=$group.SamAccountName;Member=''}
    $groupid = $group.distinguishedname
    
    if ( $members = Get-ADGroupMember $groupid ) {
            
            foreach ( $member in $members ) {

                $hash.Member = $member.Name
                New-Object psObject -Property $hash
            }
    }
    else {
        $displayname = "No Members"
        $hash.Member = $displayname
        New-Object psObject -Property $hash
    }
}

$result | Export-Csv -Path C:\temp\ADGroups.csv -NoTypeInformation

# End

相关内容