Home > Software engineering >  List of AD groups and username of users within a specific OU in PowerShell
List of AD groups and username of users within a specific OU in PowerShell

Time:02-03

Was wondering if you could help me with script.

This script would search a specific OU (let's say Disabled Users OU) and display all the AD groups all users are part of, the output to a CSV file showing Usernames and AD group names.

I have got a command that will display all AD groups of a user but I have to keep changing the username:

Get-ADPrincipalGroupMembership username_withoutdomain | select name

I have a script that requires the username entered and will display the AD group membership.

do { 
  write-host -NoNewline "Type username: "
  $user = read-host

  if ($user -eq "") { break }

  (get-aduser $user -Properties memberof).memberof |
    get-adgroup                                    |
    select -exp name
} while ($true) 

I also know it is possible to do this via command prompt:

net userusername

Thanks for all assistance.

CodePudding user response:

You can query all users under an OU by using the -SearchBase parameter, from there you can enumerate each user and then enumerate each group the user is a memberOf to generate your report:

$base = 'OU=disabledUsers,DC=domain,DC=com'
Get-ADUser -Filter * -SearchBase $base -Properties memberOf |
    ForEach-Object {
        foreach($group in $_.memberOf) {
            [pscustomobject]@{
                User     = $_.Name
                MemberOf = $group -replace '^CN=|(?<!\\),. '
            }
        }
    } | Export-Csv path\to\report.csv -NoTypeInformation

CodePudding user response:

As Santiago already stated you can query your OU with the -SearchBase. And because the user and the group membership can not be queried with one command you have to create a table as Santiago points with [pscustomobject]@{...} When I was running a daily report on users and their group membership I was running the script:

function Get-ADUserGroups{
    #$Domain = 'Domain_name'
    $users= Get-AdUser -Filter * -Properties SamAccountName, DisplayName, Description -ResultPageSize 500 |
    select SamAccountName, DisplayName, Description
    $users|
        ForEach-Object{
        $p=[ordered]@{
            UserName=$_.SamAccountName
            FullName=$_.DisplayName
            User_Description=$_.Description         
            GroupName=$null         
            Group_Description=$null         
            }
            Get-ADPrincipalGroupMembership $_.SamAccountName | 
                ForEach-Object{
                    $p.GroupName=$_.Name
                    Get-ADGroup $_ -Properties description |
                    ForEach-Object{
                    New-Object PsObject -Property $p
                    }
                }
        }
}

Get-ADUserGroups | Export-Csv -Path "Your_Path\Groups.csv" -Delimiter "|" -Encoding UTF8 -NoTypeInformation
  • Related