Get users in multiple ADgroups - powershell

I have this script that extracts the users that belong to the groups I need.
$GroupList = Get-Content C:\Scripts\grouplist.txt
$Results = foreach ($Group in $GroupList) {
$Description = Get-ADGroup -Identity $Group -Properties Description | Select-Object -ExpandProperty Description
Get-ADGroupMember -Identity $Group |
Select-Object -Property SamAccountName, Name, #{Name='GroupName';Expression={$Group}}, #{Name='Description';Expression={$Description}}
}
$Results
$Results | Export-csv -Path C:\Scripts\SecurityGroups.csv -NoTypeInformation
The problem is that I only need users in the enabled state.
And I can't. Could you help me please?
Thanks.

As mentioned per the comments you can use the Get-Aduser cmdlet after you populated your results. Here you have to filter out groups, otherwise the cmdlet will throw exceptions for every group.
$results = #()
foreach ($group in $grouplist) {
$description = (Get-ADGroup $group -Properties description).description
$members = Get-ADGroupMember $group | ?{$_.objectClass -eq "user"} | % {Get-ADUser $_ -Properties enabled}
$results += $members | ? {$_.Enabled -eq $true } | select samaccountname, name, #{name='groupname';expression={$group}}, #{name='description';expression={$description}}
}
Alternatively, you can use LDAP-filters. This option is noticeably faster since you only make one request per group, not one per user.
$results = #()
foreach ($group in $grouplist) {
$group = Get-ADGroup $group -Properties description
$members = Get-ADUser -LDAPFilter "(&(memberof=$($group.DistinguishedName))(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))"
$results += $members | select samaccountname, name, #{name='groupname';expression={$group}}, #{name='description';expression={$group.description}}
}
With LDAP-filters you could also request members of multiple groups at once, but since you want the context in which group a user was found this is not an option here..

Related

How to get-adgroup members by their Name or SamAccountName

i would like to extract members from an AD Group that contains Members and security group.
Example, Group_A:
User1
User2
User3
Group_B
When I run my script, it shows:
CN=User1,OU=Users,DC=Contoso,DC=com
CN=User2,OU=Users,DC=Contoso,DC=com
CN=User3,OU=Users,DC=Contoso,DC=com
CN=Group_B,OU=Users,DC=Contoso,DC=com
Is there another way to show their Name and/or SamAccountname?
$Groups =
#"
GroupNames;
Group_A
"# | ConvertFrom-Csv -Delimiter ';'
$ADGroups =
Foreach ($Group in $Groups){
Get-ADGroup $Group.GroupNames -Server contoso.com -Properties Members }
$ADGroups.Members
As the other helpful answers show, if you want to play safe, you can use Get-ADGroupMember to get the group membership, this would also be useful because you would be able to distinguish the ObjectClass of each member.
You could also do string manipulation over the elements (distinguishedName) of the member attribute of the AD Group by following this Q&A.
If the members of the group are on different Domains, this should work however it would be quite slow most likely.
foreach($group in $groups) {
$membership = Get-ADGroup $Group -Properties Member
$membership.Member | Group-Object { ($_ -split '(?=DC=)',2)[1] } |
ForEach-Object {
[adsi]$ldap = 'LDAP://{0}' -f $_.Name
[string]$domain = $ldap.Name
foreach($member in $_.Group) {
$obj = Get-ADObject $member -Server $domain
[pscustomobject]#{
MemberOf = $membership.Name
Domain = $domain
SamAccountName = $obj.SamAccountName
ObjectClass = $obj.ObjectClass
}
}
}
}
Get-ADGroupMember has two parameters you can use for that. samaccountname, and name.
Simply do the following:
Get-ADGroupMember -identity $ADGroup | select-object SamAccountName, Name
Or in your code snippet:
Foreach ($group in $groups) {
Get-AdGroup -identity $group | select-object Samaccountname, Name }
Of course you could add:
Get-AdGroup -identity $group | select-object Samaccountname, Name | export-csv C:\mypath\report.csv
You could run a query against the returned values using Get-ADObject since it accepts DistinguishedNames as a value and isn't limited by object class:
foreach ($Group in $Groups)
{
(Get-ADGroup $Group.GroupNames -Server contoso.com -Properties Members).Members |
ForEach-Object -Process {
Get-ADObject -Identity $_ -Properties DisplayName | Select-Object -Property DisplayName
}
}
...or, you can split the results at the desired entry:
foreach ($Group in $Groups)
{
(Get-ADGroup $Group.GroupNames -Server contoso.com -Properties Members).Members |
ForEach-Object -Process {
$_.Split(',',2).Split("=")[1]
}
}
Disclaimer: I don't have the AD Module installed on my system so I can't confirm if this is all that is needed.
The easiest way would be to expand the members property and in Get-ADGroup and then pipe it to Get-ADUser
$adUsers = Foreach ($Group in $Groups) {
Get-ADGroup $Group.GroupNames -Server contoso.com -Properties Members | Select-Object -ExpandProperty Members | Get-aduser
}

Powershell Get ADGroupMember there is in 2 Identity groups

I want 1 list with all users there are member of 2 (both) identity.
I have used this, but it returns first all users in the first identity and then the next identity.
$groups = "SMSxxx", "Personalxxxx"
$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:\Temp\GroupMemberShip.txt -NoTypeInformation
Best regards,
Peter
You can continue with your current logic and use Group-Object to find users that exist in all groups.
$groups = "SMSxxx", "Personalxxxx"
$results = foreach ($group in $groups) {
$description = (Get-ADGroup $group -Properties description).description
Get-ADGroupMember $group | select SamAccountName,Name,#{n='GroupName';e={$group}}, #{n='Description';e={$description}}
}
$results | Group-Object SamAccountName |
Where Count -eq $groups.Count | Select -Expand Group |
Export-csv C:\Temp\GroupMemberShip.csv -NoTypeInformation

Get Ad group members and properties from wildcard groups then export to csv

I'm trying to export group members and their properties from groups with names starting with XX so the output is
output
With the code i wrote i can get all the users and properties but i would also like to export the group in front of each member
$Groups = Get-ADGroup -filter {name -like "Group*"} | Select-Object Name
foreach ($Group in $Groups)
{
$Members = Get-ADGroupMember -Identity $($Group.name) -Recursive | Select-Object name
foreach ($Member in $Members )
{ Get-ADUser -Identity $($Member.name) -Properties * | Select-object * | export-csv
}
}
Thank you in advance, guys.
Store the user object in a variable, add the group as a new member of that object and pipe it to Export-CSV.
$Groups = Get-ADGroup -filter {name -like "Group*"} | Select-Object Name
foreach ($Group in $Groups) {
$Members = Get-ADGroupMember -Identity $($Group.name) -Recursive | Select-Object name
foreach ($Member in $Members) {
$UserObject = Get-ADUser -Identity $($Member.name) -Properties * | Select-Object *
$UserObject.Group = $($Group.name)
$UserObject | Export-CSV
}
}

Script to get Group Member, group starting with "ADM*"

I have a requirement to generate a CSV report to get group members. However, I there are many child domains which contains groups starting with ADM.
I need report in the following format:
GroupName User Company LasLogon CN
ADM_AM UserOne CP1
I've found one script on internet:
Get-ADGroup -Server dc1.chd1.pd.local -Filter 'Name -like "ADM*"' |
ForEach-Object{
$hash=#{GroupName=$_.Name;Member=''}
$_ | Get-ADGroupMember -ea 0 -recurs |
ForEach-Object{
$hash.Member=$_.Name
New-Object psObject -Property $hash
}
} |
sort groupname,member
This script only gives me GroupName and UserName but not other information.
How can I generate this report?
I'm not sure what "ADM_AM, UserOne, CP1" is, but i got this much for you. I'm still new to powershell so forgive me if this is a lot of code =)
$array = #()
Foreach ($group in (Get-ADGroup -Server dc1.chd1.pd.local -Filter 'Name -like "ADM*"'))
{
$hash=#{Username ='';GroupName=$group.Name;Company='';LastLogon='';CN=''}
$members = $hash.GroupName | Get-ADGroupMember -Recursive -ErrorAction SilentlyContinue
Foreach($member in $members)
{
$properties = $member.SamAccountName | Get-ADUser -Properties SamAccountName, Company, lastLogon, CN
$hash.Username = $properties.SamAccountName
$hash.Company = $properties.Company
$hash.LastLogon = $properties.lastLogon
$hash.CN = $properties.CN
$obj = New-Object psObject -Property $hash
$array += $obj
}
}
$array | Export-Csv C:\ -NoTypeInformation
Here is what I would do, Im sure you can shorten it. You shoud specify a searchbase. Once you have the members samaccountname, you can use Get-ADUser to get whatever fields you want.
$GrpArr = #()
$Groups = get-adgroup -filter {name -like "adm*"} -searchbase "ou=Groups,dc=all,dc=ca" | select samaccountname
foreach ($group in $groups)
{
$GrpArr += $group
$members = get-adgroupmember $group | select samaccountName
foreach ($member in $members)
{
$memprops = get-aduser $member -properties company
$comp = $memprops.company
$grpArr += "$member,$comp"
}
}
$grpArr | export-csv c:\temp\Groups.csv -NoTypeInformation

PowerShell script to return members of multiple security groups

I need to return all members of multiple security groups using PowerShell. Handily, all of the groups start with the same letters.
I can return a list of all the relevant security groups using the following code:
Get-ADGroup -filter 'Name -like"ABC*"' | Select-Object Name
And I know I can return the membership list of a specific security group using the following code:
Get-ADGroupMember "Security Group Name" -recursive | Select-Object Name
However, I can't seem to put them together, although I think what I'm after should look something like this (please feel free to correct me, that's why I'm here!):
$Groups = Get-ADGroup -filter 'Name -like"ABC*"' | Select-Object Name
ForEach ($Group in $Groups) {Get-ADGroupMember -$Group -recursive | Select-Object Name
Any ideas on how to properly structure that would be appreciated!
Thanks,
Chris
This is cleaner and will put in a csv.
Import-Module ActiveDirectory
$Groups = (Get-AdGroup -filter * | Where {$_.name -like "**"} | select name -expandproperty name)
$Table = #()
$Record = [ordered]#{
"Group Name" = ""
"Name" = ""
"Username" = ""
}
Foreach ($Group in $Groups)
{
$Arrayofmembers = Get-ADGroupMember -identity $Group | select name,samaccountname
foreach ($Member in $Arrayofmembers)
{
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}
$Table | export-csv "C:\temp\SecurityGroups.csv" -NoTypeInformation
If you don't care what groups the users were in, and just want a big ol' list of users - this does the job:
$Groups = Get-ADGroup -Filter {Name -like "AB*"}
$rtn = #(); ForEach ($Group in $Groups) {
$rtn += (Get-ADGroupMember -Identity "$($Group.Name)" -Recursive)
}
Then the results:
$rtn | ft -autosize
Get-ADGroupMember "Group1" -recursive | Select-Object Name | Export-Csv c:\path\Groups.csv
I got this to work for me... I would assume that you could put "Group1, Group2, etc." or try a wildcard.
I did pre-load AD into PowerShell before hand:
Get-Module -ListAvailable | Import-Module
This will give you a list of a single group, and the members of each group.
param
(
[Parameter(Mandatory=$true,position=0)]
[String]$GroupName
)
import-module activedirectory
# optional, add a wild card..
# $groups = $groups + "*"
$Groups = Get-ADGroup -filter {Name -like $GroupName} | Select-Object Name
ForEach ($Group in $Groups)
{write-host " "
write-host "$($group.name)"
write-host "----------------------------"
Get-ADGroupMember -identity $($groupname) -recursive | Select-Object samaccountname
}
write-host "Export Complete"
If you want the friendly name, or other details, add them to the end of the select-object query.