Getting AD Group Membership ADSI using PowerShell - powershell

I currently have ADSI code to get the groups a user is a part of:
$searcher = [adsisearcher]"(samaccountname=$env:USERNAME)"
$searcher.FindOne().Properties.memberof
$adgroups = $User -Replace '^cn=([^,]+).+$', '$1'
However, i am wanting to be able to choose a group and see its members. I currently have this code to get their DN and path.
$Group = [ADSI]"LDAP://cn=Test,cn=Test,dc=some,dc=domain,dc=net"
$Members = $Group.Member | ForEach-Object {[ADSI]"LDAP://$_"}
I am wanting to get other attributes if possible (name, etc.). Any help would be appreciated as i have been trying for a bit.

You already have both pieces, the first piece is finding the users in the group, the second piece is using the searcher to get properties for the users. Just use distinguishedname as the [adsisearcher] filter.
$Group = [ADSI]"LDAP://cn=Test,cn=Test,dc=some,dc=domain,dc=net"
$Group.Member | ForEach-Object {
$Searcher = [adsisearcher]"(distinguishedname=$_)"
$searcher.FindOne().Properties
}

Related

Why does -contains not seem to work with AD security permissions PSCustomObjects

I am trying to make a list of job titles and their security permissions. I would love to have two lists, a list of security permissions that are shared with more than one member with that title, and permissions that are outliers so that we can better make templates for new hires with certain job roles. I am using -contains to match security permissions with recurring security permissions but it always returns false. I am guessing that each security permission has some unique value to it per user, but even when I try to just match something like the name, it doesn't work
Here is my code.
#get all the users with a title and group them by title
$Titles = Get-ADUser -Filter * -Properties Title | Where-Object Title | Sort-Object Title | Group-Object Title
#loop through each group
foreach ($Title in $Titles){
#zero out outliers and shared permissions
$OutlierPermissions = #()
$SharedPermissions = #()
#loop through each user in each group
foreach ($User in $Title.Group){
$Permissions = #()
#get all the permissions of the user
$Permissions = Get-ADPrincipalGroupMembership $User | Sort-Object Name
#loop through each permission
foreach ($Permission in $Permissions){
#if this permission is shared by more than one user
if($OutlierPermissions -contains $Permission){
#and not already added
if($SharedPermissions -notcontains $Permission){
$SharedPermissions += $Permission
}
#else add to list of outliers
}else{$OutlierPermissions += $Permission}
}
}
}
I have also tried
-contains $Permission.Name
$Permissions = Get-ADPrincipalGroupMembership $User | Sort-Object Name | Select Name
anything to get some part of redundancy to the security permission
is there a way around this?
To put it simple $OutlierPermissions -contains $Permission will never work because $Permission is an instance of ADGroup and $OutlierPermissions is a collection of ADGroup instances and these objects are not comparable or equatable so -contains will always return $false. Instead what you want to do if pick one property of these objects that has such capabilities to have a proper comparison, in example, you can use the .ObjectGUID property.
If I'm understanding your code correctly, it could be simplified to this logic:
$map = #{}
# get all the users with the `Title` populated
foreach($user in Get-ADUser -LDAPFilter "(title=*)" -Properties Title) {
# if this `Title` has not yet been added to the hash
if(-not $map.ContainsKey($user.Title)) {
# use a `List<T>` for dynamic additions of new groups
# and a `HasShet<T>` to not duplicate additions
$map[$user.Title] = #{
ProcessedMembership = [System.Collections.Generic.HashSet[guid]]::new()
Membership = [System.Collections.Generic.List[object]]::new()
}
}
# for each group this user is a member of
foreach($group in Get-ADPrincipalGroupMembership $user) {
# if this group has not yet already been added
if(-not $map[$user.Title]['ProcessedMembership'].Add($group.ObjectGUID)) {
# add this group to the `Membership` List for this `Title`
$map[$user.Title]['Membership'].Add($group)
}
}
}
Using a Hashtable to gather all results where the Keys are the unique Titles and the Values is a nested Hashtable consisting of groups already processed ProcessedMembership (this keeps track of duplicates using a HashSet<T>) and a List<T> where you can keep a reference of all groups objects associated with each Title.

Get AD group members with ADSI - Powershell

I cannot use the Active Directory Module to get the SamAccountName of the users in a specific AD-group. How can I do this with ADSI?
I've tried:
$Group = [ADSI]"LDAP://DN of the AD group"
$Group.Member | ForEach-Object {
$Searcher = [adsisearcher]"(samAccountName=$_)"
$searcher.FindOne().Properties
}
But I see this message:
The samAccountName search filter is invalid.
How can I do this?
There are 2 ways around this as I see it, there might be an easier way of doing it though.
One is to search for all users which's memberOf attribute has the DistinguishedName of the group (this might be the less cumbersome approach):
$group = 'CN=myGroup, OU=myOU, DC=myDomain'
$searcher = [adsisearcher]"(&(objectclass=user)(objectcategory=person)(memberof=$group))"
$members = foreach($member in $searcher.FindAll()) {
$member.Properties.samaccountname
}
The other way around is using the same approach as you're using in your question:
$group = 'CN=myGroup, OU=myOU, DC=myDomain'
$adsi = [adsi]"LDAP://$group"
$members = foreach($member in $adsi.member) {
$isUser = [adsi]"LDAP://$member"
if('person' -in $isUser.objectclass) {
$isUser.samaccountname
}
}
Similar as the one above, but using adsisearcher, not sure which one would be more efficient in this case:
$members = foreach($member in $adsi.member) {
$check = [adsisearcher]"(&(distinguishedname=$member)(objectclass=user)(objectcategory=person))"
if($isUser = $check.FindOne()) {
$isUser.Properties.samaccountname
}
}
I ran this modified version of your code on my own system, so I could see what the search string actually looked like:
$Group = [ADSI]"LDAP://DN of the AD group"
$Group.Member | ForEach-Object {
$searchKey = "(samAccountName=$_)"
$searchKey
$Searcher = [adsisearcher]$searchKey
# $searcher.FindOne().Properties
}
Note the point where I let $searchKey come to the console. When I do this, I see values with the full distinguished name instead of just samAccountName. Based on this result I changed the code to look for that value instead of samAccountName, and then I saw (presumably) expected results:
$Group = [ADSI]"LDAP://DN of the AD group"
$Group.Member | ForEach-Object {
$Searcher = [adsisearcher]"(distinguishedName=$_)"
$searcher.FindOne().Properties
}

Check to See if User is part of any of certain AD groups

I'm fairly new to powershell. I'm hoping to get direction on how I can task to work.
So part of my new hire script is to ensure a user account that gets created is surely added to Office ALL group. If it doesn't get added for some reason, I need a way to identity which account didn't get added.
We have office group office name that starts with Province/state Like ON,BC,AB and end with -ALL#jbalatest.com
$ADgroupofAlloffices= $provincearray | ForEach-Object -process {Get-ADGroup -Filter "mail -like '$_-*'" -Properties Mail |
Where-Object {$_.Mail -LIKE "*-ALL#jbalatest.com"} |
Select-Object DistinguishedName | Sort-Object -Property Samaccountname}
This is my query to get all the groups by DistinguishedName. I have than more 30 groups.
Now I need away to check to see if the new hire account is part of this group as part of the final portion of over all script.
$user_groups = (Get-ADUser -Identity $ADUseraccount -Properties memberof | Select-Object memberof).memberof
I know with this I can get all the group of users.
How I check if AD user is part any of these office groups and let me know if user is not part any of these groups.
Let me know where need to do more search on finding solution for this. Scratching my head here.
Several ways to do this, here is one, first the way you're getting the Office Groups can be optimized using AD Filtering only, with some string manipulation. You can iterate over the $provArray to generate an array of strings which then gets joined and combined into a single LDAP Filter, in example with the Provinces / States provided in your question the filter would be something like this:
(|(mail=ON*-ALL#jbalatest.com)(mail=BC*-ALL#jbalatest.com)(mail=AB*-ALL#jbalatest.com))
Then after you query for all the groups, you can get an array with the DistinguishedName of all these groups ($officeGroups) which we can use to compare with the memberOf attribute of the user:
$provArray = 'ON', 'BC', 'AB' # and more here
$filter = foreach($i in $provArray) {
"(mail=$i*-ALL#jbalatest.com)"
}
$filter = "(|$(-join $filter))"
$officeGroups = (Get-ADGroup -LDAPFilter $filter).DistinguishedName
$user = (Get-ADUser 'someuser' -Properties memberof).memberof
if($user.where{ $officeGroups -contains $_ }) {
'user is a member of at least one office group'
# do something here
}
else {
'user is not a member of any office groups'
# do something here
}
Since you already have the distinguished name of all of the groups you're interested, you can just test if any of the groups that the user is a member of is in that list and go from there.
$OfficeGroup = $ADgroupofAlloffices | Where{$_.DistinguishedName -in $user_groups}
If(!$OfficeGroup){Write-Warning "User is not in an office group"}

Powershell Azure See Cannot See what groups a contact is in

I am trying to see the groups a contact is apart of. To provide some background, the contact is hidden in the directory of the tenet I am looking in because it is the alias of a sister tenet that the user is actually apart of. I am using PS and the cmd runs but displays no results. Can someone tell me where I may be going wrong? The users email address is stored in variable string called contact
Code:
Get-MsolGroup -All | Where-Object {$_.Members -contains $contact}
When I enter this command in PowerShell I do not get any results displayed
Untested but, I believe this should work. It should return the ObjectId and DisplayName of the Groups where $contact is a member of.
$groups = Get-MsolGroup -All
$contact = 'someUser#someCompany.com'
foreach($group in $groups)
{
$members = Get-MsolGroupMember -GroupObjectId $group.ObjectId
if($contact -in $members.EmailAddress)
{
$group | Select-Object ObjectId, DisplayName
}
}

Foreach in foreach (nested)

I'm trying to loop all disabled users through an array of groups to check if the users have membership in any of the listed groups. My thought is that for every user in the list loop them through and check if they are present in one of the listed groups. That would require nesting foreach loops, right? The output I get is like this:
...
user1
user2
user3
is not a member of group1
Here is the source code:
$dUsers = Get-ADUser -Filter {enabled -eq $false} |
FT samAccountName |
Out-String
$groups = 'Group1', 'Group2'
foreach ($dUser in $dUsers) {
foreach ($group in $groups) {
$members = Get-ADGroupMember -Identity $group -Recursive |
Select -ExpandProperty SamAccountName
if ($members -contains $dUsers) {
Write-Host "[+] $dUser is a member of $group"
} else {
Write-Host "[-] $dUser is not a member of $group"
}
}
}
I'm pulling my hair because I feel like there is a simple solution, but I'm lost.
Update:
I wanted to put all disabled users in variable $dUsers.
It actually works if I manually put users in the variable like this:
$dUsers = 'user1','user2','user3'
Which gives me the following output:
user1 is not a member of group1
user1 is not a member of group2
user2 is not a member of group1
user2 is not a member of group2
...
This makes me question how it gets "foreached" when the variable is:
$dUsers = Get-ADUser -Filter {enabled -eq $false} |
FT samAccountName |
Out-String
Anyone got a clarification on that?
Update:
This is the final code. It takes a long time to run, even with only two groups.
$dUsers = Get-ADUser -Filter {enabled -eq $false} | Select-Object -Expand SamAccountName
$groups = 'Group1', 'Group2'
Write-host '[+] Checking if any disabled user is member of any SSL groups'
Write-host '[+] This might take a while. Get a coffee!'
write-host '[+] Running...'`n
foreach ($dUser in $dUsers) {
foreach ($group in $groups) {
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty SamAccountName
if($members -contains $dUser) {
Write-Host "$dUser is a member of $group"
} Else {
# Remove or comment out the line below to get a clutterfree list.
# Write-Host "$dUser is not a member of $group"
}
}
}
You have two issues in your code:
You're creating a single string from the Get-ADUser output. Piping the output of that cmdlet through Format-Table (alias ft) and then Out-String creates one string with a tabular display of all matching account names including the table header.
If you output $dUsers in a way that makes beginning and end of a string visible you'd see something like this (the leading and trailing == marking the beginning and end):
PS> $dUsers | ForEach-Object { "==$_==" }
==samAccountName
--------------
user1
user2
user3==
Since there is no account with a username matching this string no match can be found in any group and you're getting the output you observed.
This misuse of Format-* cmdlets is a common beginner's mistake. People get a nicely formatted string output and then try to work with that. ONLY use Format-* cmdlets when you're presenting data directly to a user, NEVER when further processing of the data is required or intended.
What you actually want is not a string with a tabular display of usernames, but an array of username strings. You get that by expanding the SamAccountName property of the user objects you get from Get-ADUser.
$dUsers = Get-ADUser ... | Select-Object -Expand SamAccountName
The second issue is probably just a typo. Your condition $members -contains $dUsers won't work, since both $members and $dUsers are arrays (after fixing the first issue, that is). The -contains operator expects an array as the first operand and a single value as the second operand.
Change
$members -contains $dUsers
to
$members -contains $dUser
Depending on what PowerShell version you are on, there is a cmdlet for this use case and others.
As for
I'm Trying to loop all disabled users
Just do...
Search-ADAccount -AccountDisabled |
Select-Object -Property Name, Enabled,
#{Name = 'GroupName';Expression = {$_.DistinguishedName.Split(',')[1] -replace 'CN='}}
# Results
Name Enabled GroupName
---- ------- ---------
...
testuser2 NewTest False Users
Guest False Users
Or different cmdlet…
# Get disabled users and their group membership, display user and group name
ForEach ($TargetUser in (Get-ADUser -Filter {Enabled -eq $false}))
{
"`n" + "-"*12 + " Showing group membership for " + $TargetUser.SamAccountName
Get-ADPrincipalGroupMembership -Identity $TargetUser.SamAccountName | Select Name
}
# Results
...
------------ Showing group membership for testuser1
Domain Users
Users
------------ Showing group membership for testuser2
Domain Users
As for ...
an array of Groups
Just select or filter the DN for the group name you want using the normal comparison operators.
As for...
Unfortunately I'm not well versed in powershell.
… be sure to spend the necessary time to get ramped up on it, to limit the amount of misconceptions, confusions, errors, etc. that you are going to encounter. There are plenty of no cost / free video and text-based training / presentations all over the web.
Example:
Videos
Use tools that will write the code for you that you can later tweak as needed.
Step-By-Step: Utilizing PowerShell History Viewer in Windows Server 2012 R2
Learning PowerShell with Active Directory Administrative Center (PowerShell History Viewer)
As well as plenty of sample scripts and modules via the MS PowerShell Script / Module Gallery.
There are two commands for the AD Groups.
First I see that you want the membership of the disabled users that is easy.
#Get the dissabled users from your AD with all their attributes (properties and select)
$dUsers = Get-ADUser -Filter {Enabled -eq $false} -Properties * | Select *
#Run a loop for each user to get the group membership
Foreach ($User in $dUsers) {
$User = $User.SamAccountName
Get-ADUser $User -Properties * | Select Name, SamAccountName, MemberOf | Format-Table -Wrap # > "D:\test\$user.txt" -HideTableHeaders
}
This one can work but I don't like the output that we get.
I prefer to run the groupmembership command and check the users.
$GroupMembers = Get-ADGroupMember "groupname"| Select Name, SamAccountName
ForEach ($User in $GroupMembers)
{
$UserProperties = Get-ADUser $User.SamAccountName -Properties * | select *
If ($UserProperties.Enabled -eq $False) {
Write-Host $UserProperties.SamAccountName
}
}
Edit:
Let me know if those fits you.
Kind regards.
The first thing you should try to check is whenever you are only interested in direct memberships or indirect ones as well. Depending on the answer the options you got availabel change a bit. You probably will encounter Distinguished Names while working on this so check out what they are if you don't know (mostly a path for an object).
If it's only direct memberships using memberOf with Get-ADUser should be sufficient. The memberOf attribute contains every direct group membership of the user with the full Distinguished Name of the group.
Get-ADUser test -Properties MemberOf | Select-Object -ExpandProperty memberOf
You can match the groups you're looking for in various ways. You could get the whole Distinguished Name of those groups or you could do a partial match. It's up to you to decide how to proceed.
If you need the indirect memberships as well you might want to split up your code to make it easier for yourself. For instance you could first find the users and save them. Afterwards find all group members of those groups (You already got that with Get-ADGroupMember) and finally compare the two.
Currently for every user you build the whole list of group members again. This approach would save a few resources as you wouldn't be doing the same queries over and over again.
Finally you could also use the MemberOf approach but get the list of every direct and indirect membership of a user using an LDAP query.
$dn = (Get-ADUser example).DistinguishedName
$userGroups = Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $dn)
This approach uses a LDAP search query. It can be quite complex, you could also only check for one one of the groups by modifying it a bit.
In the end even your current approach should work. The problem is that you're comparing the AD object against the list of SAM Accountnames. You would need to check for the SAM Accountnames as well.
if($members -contains $dUsers.SamAccountName)
if($members -contains $dUsers | Select-Object -ExpandProperty SamAccountName)
One of these should work if you change your $dUsers as well. As it currently is you end up with a giant string. You probably can check that by checking $dUsers.length. Just drop the Format-Table and Out-String.