【问题标题】:Script to list users and all the groups they are members of列出用户及其所属的所有组的脚本
【发布时间】:2017-02-21 08:25:20
【问题描述】:

我已经启动了一个脚本,它将 AD 中的用户名与 CSV 中的特定职位进行比较,然后列出该用户所属的所有组(以及组内的组)。

我检查了第一条评论下的功能,它按预期工作,列出了用户的所有组。

脚本的下一部分没有按预期工作,当我尝试使用用户列表的输出作为我的函数的变量时,我只得到所有用户所属的组列表,而不是组和用户。

现在我得到以下结果:

Group1
第 2 组
第 3 组
第 2 组
第 3 组
第 4 组

我的理想输出应该是:

用户成员
---- --------
鲍勃组 1、组 2、组 3....
吉姆 Group2、Group3、Group4....

代码:

#Function to recursively check account for group membership
function Get-SubGroups ($account)
{
    $ErrorActionPreference = "SilentlyContinue"

    $groups = Get-ADPrincipalGroupMembership $account
    $allGroups =$null

    while ($groups)
    {
        $allGroups += $groups.Name
        $groups = $groups.Name | Get-ADPrincipalGroupMembership   
    }
    $allGroups
}

#CSV with list of job titles and command to get the first user with a job title
$titles = Get-Content 'B:\JobTitles.csv'

#Command to get the list of groups for each user
$users = foreach ($title in $titles)
{
    Get-ADUser -Filter 'Title -Like $title' -Properties Name, SamAccountName, MemberOf, Title | select -First 1
}

foreach ($user in $users)
{
    Get-SubGroups $user | Write-Output
}

【问题讨论】:

    标签: powershell csv foreach active-directory


    【解决方案1】:

    你的意思是这样的吗:

    #Function to recursively check account for group membership
    function Get-SubGroups ($account)
        {
        $ErrorActionPreference = "SilentlyContinue"
    
            $groups = Get-ADPrincipalGroupMembership $account
            $allGroups =$null
    
            While($groups)
        {
            $allGroups += $groups.Name
            $groups = $groups.Name | Get-ADPrincipalGroupMembership   
        }
            $allGroups
        }
    
    #CSV with list of job titles and command to get the first user with a job title
    $titles = Get-Content 'B:\JobTitles.csv'
    
    $users = @()
    
    foreach ($title in $titles)
    {
        $users += Get-ADUser -Filter 'Title -Like $title' -Properties Name, SamAccountName, MemberOf, Title | select -First 1
    } 
    
    $users | Format-Table -Wrap @{Expression={$_.Name};Label="User";width=25},
    @{Expression={[string[]](Get-SubGroups $_) -join ' '};Label="MemberOf"} | Write-Output
    

    输出将是:

    User                      MemberOf                                                                                                                         
    ----                      --------                                                                                                                         
    SomeUser                  Group1 Group2 Group3
    SomeUser2                 Group2 Group3
    

    【讨论】:

    • 我已经测试过,这适用于我的环境,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 2023-03-06
    • 2012-03-16
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    相关资源
    最近更新 更多