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.
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:
$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