用于列出用户及其所属组的脚本

时间:2016-10-12 13:41:33

标签: powershell csv foreach active-directory

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

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

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

现在我得到以下结果:

Group1
Group2
Group3
Group2
Group3
Group4

我的理想输出将是:

User  MemberOf
----  --------
Bob   Group1, Group2, Group3....
Jim   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
}

1 个答案:

答案 0 :(得分:2)

你是说这样的意思吗?

#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