Home > Net >  PowerShell Script to display all users part of AD security groups within an OU in AD
PowerShell Script to display all users part of AD security groups within an OU in AD

Time:03-09

I am new to PowerShell I am trying to display all AD security groups within a certain OU and to display each user part of that security group.

I want to show username and name and the security group name to a CSV file.

I have managed to get this information but I had to manually add the AD security group name within the script itself:

$groups = "GroupName1", "GroupName2", "GroupName3", "GroupName4", "GroupName5"

$results = foreach ($group in $groups) {
    Get-ADGroupMember $group | select samaccountname, name, @{n='GroupName';e={$group}}, @{n='Description';e={(Get-ADGroup $group -Properties description).description}}
}

$results

$results | Export-csv C:\Users\Sam\Desktop\Users.csv -NoTypeInformation 

The above script outputs the information I require but as stated above I have to manually enter the Security GroupName within the script itself.

I think the command I need to use is Get-ADGroup

Any help is appreciated thanks.

CodePudding user response:

You can use Get-ADGroup -Filter * -SearchBase 'OUdnHere' to search for all groups under your desired Organizational Unit, then you can simply apply the same logic you already have:

  1. Loop over the Groups
  2. Get their memberships
  3. Construct the output
  4. Export to CSV
$ou = 'distinguished name of my OU here'
Get-ADGroup -Filter * -SearchBase $ou -Properties Description | ForEach-Object {
    foreach($member in Get-ADGroupMember $_) {
        [pscustomobject]@{
            SamAccountName = $member.SamAccountName
            Name           = $member.Name
            GroupName      = $_.Name
            Description    = $_.Description
        }
    }
} | Export-csv C:\Users\Sam\Desktop\Users.csv -NoTypeInformation 

CodePudding user response:

Try something like this (add the correct dn for the OU of course):

$Groups = Get-AdGroup -SearchBase "ou=OuName,DC=contoso,DC=local" | Select -ExpandProperty Name

Or somewhat shorter and easier to read according to me:

$Groups = (Get-AdGroup -SearchBase "ou=OuName,DC=contoso,DC=local").Name

Untested code, but you get the gist of it.

  • Related