powershell - Powershell :获取成员资格和组的成员数

如果该组的成员数量少于 3,我想像下面这样导出这些成员。顺便说一句,也有嵌套组。

我想要的输出:

Members,Group Name,Members Count,Members
NO,Group01,10
NO,Group02,1,user01
YES,Group03,2,user01;user02

这是我的脚本:

Import-Csv -Path "C:\tmp\unused.csv" | ForEach-Object {
    $out = @{ 'Group Name' = $_.Name }
    if((Get-ADGroup $_.Name -Properties Member).Member) {
        $out['Members'] = 'YES'
    }
    else {
        $out['Members'] = 'NO'
    }
    [pscustomobject] $out
} | Export-Csv "C:\tmp\export.csv" -NoTypeInformation -Encoding UTF8

回答1

这应该会给您预期的结果,请注意 Get-ADGroupMember 将为每个组递归返回所有成员,如果这不是您想要的,请删除 -Recursive 参数。

另请注意,这可能会返回任何对象类作为组的成员(计算机、其他组、用户、服务帐户...),您只想将用户定位为成员,请使用以下命令:

$members = @(Get-ADGroupMember $_.Name -Recursive).where{ $_.objectClass -eq 'user' }

代码

Import-Csv -Path "C:\tmp\unused.csv" | ForEach-Object {
    $out = [ordered]@{
        'HasMembers'    = ''
        'Group Name'    = $_.Name
        'Members Count' = ''
        'Members'       = ''
    }
    # using `-Recursive` since there can be nested groups
    $members = @(Get-ADGroupMember $_.Name -Recursive)
    # if count is 0
    if(-not $members.Count) {
        $out['HasMembers'] = 'NO'
    }
    # if count is lower than 3 and greater than 0
    elseif($members.Count -lt 3) {
        $out['HasMembers'] = 'YES'
        $out['Members'] = $members.Name -join ';'
    }
    # if count is greater than 2
    else {
        $out['HasMembers'] = 'YES'
    }
    $out['Members Count'] = $members.Count
    [pscustomobject] $out
} | Export-Csv "C:\tmp\export.csv" -NoTypeInformation -Encoding UTF8

相似文章

最新文章