Powershell Adding users within groups to cross forest groups - powershell

This script works without error now, but the problem is that when several groups in the searchbase are found, the script will add all users from all groups to the cross forest target groups.
So for example:
ForestAGroup1 = contains 2 users
ForestAGroup2 = contains 2 users
::runs script::
now...
ForestBGroup1 = contains 4 users
ForestBGroup2 = contains 4 users
The ForestBGroup1/2 needs to contain the same identical users as ForestAGroup1/2.
Here is the script for reference:
$creds = Get-Credential
$Groups = Get-ADGroup -Properties * -Filter * -SearchBase "OU=TEST,OU=Shop Print Groups,OU=User,OU=domain Groups,DC=domainA,DC=com" | export-csv c:\temp\test.csv
$Groups = Get-ADGroup -Properties * -Filter * -SearchBase "OU=TEST,OU=Shop Print Groups,OU=User,OU=domain Groups,DC=domainA,DC=com"
Foreach($G In $Groups)
{
#Display group members and group name
Write-Host $G.Name
Write-Host "-------------"
$G.Members
#Add members to domainB group
$domainGMembers = import-csv C:\temp\test.csv | ForEach-Object -Process {Get-ADGroupMember -Identity $_.CN} | Select-Object samaccountname | export-csv c:\temp\gmembers.csv
$domainDNUser = import-csv C:\temp\gmembers.csv | ForEach-Object -Process {Get-ADUser $_.samaccountname -Server "domainA.com" -properties:Distinguishedname}
import-csv C:\temp\gmembers.csv | ForEach-Object -Process {Add-ADGroupMember -Server "domainB.com" -Identity $G.Name -Members $domainDNUser -Credential $creds -Verbose}
}

What are you doing?
You export to csv, but still try to save it to a variable
You search twice
You add all members from ALL groups in TEST-OU to every group in domainB
You waste time on saving and reading data that you already have in memory
You search for the user-object to get SamAccountName when you already have something ten times better, the DN. Then you use that SamAccountName to find the DN.
Try this (untested):
$creds = Get-Credential
$Groups = Get-ADGroup -Properties Members -Filter * -SearchBase "OU=TEST,OU=Shop Print Groups,OU=User,OU=domain Groups,DC=domain,DC=com"
Foreach($G In $Groups)
{
#Display group members and group name
Write-Host $G.Name
Write-Host "-------------"
$G.Members
#Add members to domainB group
$G.Members |
Get-ADUser -Server fairfieldmfg.com |
ForEach-Object { Add-ADGroupMember -Server "domainB.com" -Identity $G.Name -Members $_ -Credential $creds -Verbose }
}
I used a foreach-loop to run the Add-ADGroupMember because it usually fails in the middle of a group of members if it finds on the already is a member, but if we add them one at a time you get around that (or you could do a search and exclude those already in the group).
You may want to add -ErrorAction SilentlyContinue to Add-ADGroupMember to ignore those errors when you know the script works as it should.

Related

PowerShell - add an exclusion into Remove-ADGroupMember command?

When somebody leaves my organization, we remove all AD group memberships apart from the PrimaryGroup which is Domain Users. We often process these in batches, so pull the affected usernames from a CSV file.
I have the following code, and while it does the job of deleting all group memberships, I get an error for each user:
The user cannot be removed from a group because the group is currently the user's primary group
Whilst it does the job, how can I "clean up" the process to avoid this message each time? Is there a way to exclude Domain Users from the groups it removes the user from, or should I do this another way?
$users = Import-Csv "c:\temp\leavers.csv"
foreach ($user in $users) {
Get-ADPrincipalGroupMembership -identity $user.username | foreach {Remove-ADGroupMember $_ -Members $user.username -Confirm:$false}
}
You can use Where-Object for filtering those groups that are not in an array of groups to exclude. In case you only want to filter for 1 specific group, you would use -NE instead of -NotIn in below example.
$groupToExclude = 'Domain Users', 'someOtherGroup'
$users = Import-Csv "c:\temp\leavers.csv"
foreach ($user in $users) {
try {
Get-ADPrincipalGroupMembership -Identity $user.username |
Where-Object Name -NotIn $groupToExclude |
Remove-ADGroupMember -Members $user.username -Confirm:$false
}
catch {
Write-Warning $_.Exception.Message
}
}
If you get the ADUser object before the ADGroup memberships, you can get the PrimaryGroup of the user and ensure that the list of groups to remove from are not its PrimaryGroup:
$users = Import-Csv "c:\temp\leavers.csv"
foreach ($user in $users) {
$primaryGroup = ( Get-ADUser $user.UserName -Properties PrimaryGroup ).PrimaryGroup
Get-ADPrincipalGroupMembership -Identity $user.UserName | Where-Object {
$_ -ne $primaryGroup
} | ForEach-Object {
Remove-ADGroupMember $_ -Members $user.username -Confirm:$False -WhatIf
}
}
Since this has the potential to be a very destructive command, I have included a safeguard in the example above. Remove the -WhatIf parameter from Remove-ADGroupMember to actually perform the removal.
I'd propose a slightly different approach - just drop Get-ADPrincipalGroupMembership altogether. For example:
$users = Import-Csv -Path c:\temp\leavers.csv
foreach ($user in $users) {
# Assuming DN is not in the csv...
$distinguishedName = (Get-ADUser -Identity $user.UserName).DistinguishedName
Get-ADGroup -LdapFilter "(member=$distinguishedName)"
# Alternatively, just pipe memberOf property to Get-ADGroup...
(Get-ADUser -Identity $user.UserName -Property MemberOf).MemberOf |
Get-ADGroup
}
That way you don't have to filter out something you insisted on getting (by using above mentioned cmdlet).

Is there a better way to get AD group members for a given list of AD group ObjectGUIDs?

I have a list of ObjectGUID's (49 of them) stored in a CSV, and I'm outputting a CSV which contains a listing of all members of those groups in the following format: "LastName, FirstName" , "AD Group Name"
I have it working (most of the time; sometimes I get IOException errors from the Add-Content cmdlt), but it is very slow (takes ~30 minutes for 8000 members). I don't have a lot of experience with Powershell , but I feel like there is a better/more efficient way of doing this. Any ideas on how to make this more efficient?
Note: I use the "-Server" switch because I actually have to run this script across a couple different domains, so the code I've pasted is duplicated twice in my original code, with a different CSV input, and a different domain passed to the "-Server" switch.
#read in CSV of ObjectGUIDs
$guids = Import-CSV .\ObjectGUIDs.csv
#loop through each AD group
foreach($group in $guids) {
$group_name = Get-ADObject -identity $group.objectGUID -server myDomain
$group_name = $group_name.Name
#get list of users in current group
$users = get-adgroupmember -server myDomain -identity
$group.ObjectGUID | where {$_.objectclass -eq 'user'}
#loop through each user of the current group
foreach ($user in $users) {
#get display name of current user
$display_name = get-aduser -identity $user.objectGUID -server
myDomain -properties DisplayName
#build the current row
$row = ('"' + $display_name.DisplayName + '"' + ',' + '"' +
$group_name + '"')
add-content -path "C:\Path\to\output.csv" -value $row
}
}
As I said above, this usually works, but takes a long time.
Gathering data in a [PSCustomObject] and using Export-Csv only once should be much more efficient.
## Q:\Test\2018\12\27\SO_53946702.ps1
$guids = Import-CSV .\ObjectGUIDs.csv
$CsvFile = "C:\Path\to\output.csv"
$Server = myDomain
$CsvData = foreach($group in $guids) {
$GroupName = (Get-ADObject -identity $group.objectGUID -server $Server).Name
#get list of users in current group
$users = Get-ADgroupMember -Server $Server -Identity $group.ObjectGUID |
Where-Object ObjectClass -eq 'user'
foreach ($user in $users) {
[PSCustomObject]#{
DisplayName = (Get-ADuser -Identity $user.objectGUID -server $Server -Properties DisplayName).DisplayName
GroupName = $GroupName
}
}
}
$CsvData | Export-Csv $CsvFile -NoTypeInformation

Get-ADUser - find both ForeignSecurityPrincipals and users of a subDomain

We have a (2 way) trust relationship between 2 forests:
acme.com
someOtherForest.com
We have several subDomains in forest acme.com
domain1.acme.com
domain2.acme.com
I have (nested) groups in domain1.acme.com that contain both users in domain2.acme.com and foreignSecurityPrincipals from someOtherForest.com.
The server I am connected to uses a DC (dc1) on domain1.acme.com.
I have been using the following script to output all the members from a given group (recursively). It outputs foreignSecurityPrincipals as well as domain1 users perfectly fine, but errors on members who are from domain2:
$Groups = Get-ADGroup -Properties * -Filter * -SearchBase "CN=app-users,OU=app,DC=domain1,DC=acme,DC=com"
Foreach($G In $Groups) {
$members = Get-ADGroupMember $G -recursive | Get-ADUser -Properties Mail |Select-Object DistinguishedName,sAMAccountName, Mail |
Export-CSV -Path C:\output.csv -NoTypeInformation
}
If I add -server dc1:3268 (the GC of the DC) to the Get-AdUser section, then domain2 members are output fine, however it errors on foreignSecurityPrincipals.
Is there a way to output both foreignSecurityPrincipals and members from all subDomains of acme.com?
You're on the right track with using the GC port since that will take care of your forest.
But the problem is still the Foreign Security Principals. The documentation for Get-ADGroupMember says that it outputs "principal objects that represent users, computers or groups". So it'll only work for those three types of objects, not Foreign Security Principals.
That of course makes things a little more difficult for two reasons:
You don't have the ability to use the -Recursive property, so you have to handle that manually.
You still have to resolve the Foreign Security Principals.
This tipped me off that we can use Get-ADObject instead.
I was bored, so I wrote this for you. We do have a similar setup of domains here, so I was able to test it. But keep in mind that the domains are hard-coded. It assumes any foreign security principal will be on that one domain and not any other. So make sure you update the domain names (3 places).
It resolves the external accounts by taking the objectSid from the Foreign Security Principal, which is actually the SID of the account on the external domain, and using that to look up the user on that domain.
function Get-Members {
param([Microsoft.ActiveDirectory.Management.ADGroup]$group)
$members = $group | Select-Object -ExpandProperty Members | Get-ADObject -Server dc1:3268 -Properties Mail,SamAccountName,objectSid,ObjectClass
$returnMembers = New-Object System.Collections.ArrayList
foreach ($member in $members) {
if ($member.ObjectClass -eq "ForeignSecurityPrincipal") {
$returnMembers.Add((Get-ADUser -Server someOtherForest.com $member.objectSid -Properties Mail,SamAccountName)) | Out-Null
} elseif ($member.ObjectClass -eq "Group") {
$nestedMembers = (Get-Members ($member | Get-ADGroup -Properties Members))
if ($nestedMembers) {
if ($nestedMembers.Count -gt 1) {
$returnMembers.AddRange($nestedMembers) | Out-Null
} else {
$returnMembers.Add($nestedMembers) | Out-Null
}
}
} else {
$returnMembers.Add($member) | Out-Null
}
}
return $returnMembers
}
$Groups = Get-ADGroup -Server dc1:3268 -Properties Members -Filter * -SearchBase "CN=app-users,OU=app,DC=domain1,DC=acme,DC=com"
Foreach($G In $Groups) {
$members = Get-Members $G |Select-Object DistinguishedName,sAMAccountName, Mail |
Export-CSV -Path C:\output.csv -NoTypeInformation
}
Gabriel Luci's answer helped me edit my original script, to create a fast AD query that produces the same result set.
This is working for our setup, but I cannot be sure it would work for every AD setup.
WARNING: Errors that occur are suppressed using the -erroraction 'silentlycontinue' option.
This will display all members (domain, subdomain, and trusted Forest domains) of a group (in the server's domain) including nested groups. Each user will only appear once, regardless of how many nested groups they are a member of.
$set = New-Object 'System.Collections.Generic.HashSet[Microsoft.ActiveDirectory.Management.ADUser]'
$Groups = Get-ADGroup -Properties * -Filter * -SearchBase "CN=app-users,OU=app,DC=domain1,DC=acme,DC=com"
Foreach($G In $Groups)
{
$members = Get-ADGroupMember $G -recursive | Get-ADUser -Properties Mail -erroraction 'silentlycontinue'
$subDomainMembers = Get-ADGroupMember $G -recursive | Get-ADUser -Server dc1:3268 -Properties Mail -erroraction 'silentlycontinue'
Foreach ($i In $members){
$set.Add($i)| Out-Null
}
Foreach ($i In $subDomainMembers){
$set.Add($i)| Out-Null
}
}
$set |Select-Object -Unique DistinguishedName,sAMAccountName, Mail | Export-CSV -Path C:\output.csv -NoTypeInformation

Powershell ALL AD Users and their Group Memberships

Looking to write a powershell script that will pull ALL AD users, their group memberships and the groups Description Field.
I have been using two scripts to accomplish this, and just manually manipulating them in excel. Any attempt to combine them has been met with error.
Import-module activedirectory
$ou ="DC=blah,DC=blah"
Get-ADGroup -Filter * -SearchBase $OU | select -expandproperty name | % {
$group= "$_"
$result += Get-ADGroupMember -identity "$_" | select #{n="Group";e={$group}},name
}
$result | export-csv 'c:\users\membership.csv' -notypeinformation
And:
Import-Module ActiveDirectory
$Groups = ForEach ($G in (Get-ADGroup -Filter * ))
{
$UN = Get-ADGroup $G -Properties Description | select name, description
New-Object PSObject -Property #{
Desc=$UN.description
Name=$UN.name
}
}
$Groups | Export-CSV C:\users\GroupDesc.csv -notypeinformation
I hope i've got this right, this will pull all users from AD and get the groups each one is a member of (including the groups description). After everything is done it puts the info into a csv.
Import-Module ActiveDirectory
$OU = "DC=blah,DC=blah"
#$allUsers = Get-ADUser -LDAPFilter "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))" # all users that are enabled
#$allUsers = Get-ADUser -Filter * # all users
$allUsers = Get-ADUser -Filter * -SearchBase $OU
$results = #()
foreach($user in $allUsers)
{
$userGroups = Get-ADPrincipalGroupMembership -Identity $user
foreach($group in $userGroups)
{
$adGroup = Get-ADGroup -Identity $group -Properties Description
$results += $adGroup | Select-Object -Property #{name='User';expression={$user.sAMAccountName}},Name,Description
}
}
$results | Export-Csv -Path 'C:\Membership.csv' -NoTypeInformation -Encoding Unicode

How to get all groups that a user is a member of?

PowerShell's Get-ADGroupMember cmdlet returns members of a specific group. Is there a cmdlet or property to get all the groups that a particular user is a member of?
I fixed my mistake: Get-Member should be Get-ADGroupMember.
Get-ADPrincipalGroupMembership will do this.
Get-ADPrincipalGroupMembership username | select name
name
----
Domain Users
Domain Computers
Workstation Admins
Company Users
Company Developers
AutomatedProcessingTeam
Single line, no modules necessary, uses current logged user:
(New-Object System.DirectoryServices.DirectorySearcher("(&(objectCategory=User)(samAccountName=$($env:username)))")).FindOne().GetDirectoryEntry().memberOf
Kudos to this vbs/powershell article: http://technet.microsoft.com/en-us/library/ff730963.aspx
A more concise alternative to the one posted by Canoas, to get group membership for the currently-logged-on user.
I came across this method in this blog post: http://www.travisrunyard.com/2013/03/26/auto-create-outlook-mapi-user-profiles/
([ADSISEARCHER]"samaccountname=$($env:USERNAME)").Findone().Properties.memberof
An even better version which uses a regex to strip the LDAP guff and leaves the group names only:
([ADSISEARCHER]"samaccountname=$($env:USERNAME)").Findone().Properties.memberof -replace '^CN=([^,]+).+$','$1'
More details about using the [ADSISEARCHER] type accelerator can be found on the scripting guy blog: http://blogs.technet.com/b/heyscriptingguy/archive/2010/08/24/use-the-powershell-adsisearcher-type-accelerator-to-search-active-directory.aspx
Old school way from CMD:
net user mst999 /domain
(GET-ADUSER –Identity USERNAME –Properties MemberOf | Select-Object MemberOf).MemberOf
This should provide you the details for current user. Powershell not needed.
whoami /groups
If you cannot get Get-ADPrincipalGroupMembership to work for you could try logging in as that user then use.
$id = [Security.Principal.WindowsIdentity]::GetCurrent()
$groups = $id.Groups | foreach-object {$_.Translate([Security.Principal.NTAccount])}
$groups | select *
While there are many excellent answers here, there is one which I was personally looking for that was missing. Once I figured it out - I thought I should post it in case I want to find it later, or it actually manages to help someone else at some point:
Get-ADPrincipalGroupMembership username | Format-Table -auto
A second approach for presenting this is to specify the individual columns you are interested in eg:
Get-ADPrincipalGroupMembership username | select name, GroupScope, GroupCategory
This gives all the AD groups the username belongs to - but also presents all of the default properties of each group formatted nicely as a table.
The key benefit this gives you is you can see at a glance which are distribution lists, & which are Security groups. You can further see at a glance which are Universal, which are DomainLocal & which are Global.
Why would you care about this last bit?
Universal group is a security or distribution group that contains
users, groups, and computers from any domain in its forest as
members. You can give universal security groups rights and
permissions on resources in any domain in the forest.
Global group is a group that can be used in its own domain, in member
servers and in workstations of the domain, and in trusting domains.
In all those locations, you can give a global group rights and
permissions and the global group can become a member of local groups.
However, a global group can contain user accounts that are only from
its own domain.
Domain local group is a security or distribution group that can
contain universal groups, global groups, other domain local groups
from its own domain, and accounts from any domain in the forest. You
can give domain local security groups rights and permissions on
resources that reside only in the same domain where the domain local
group is located.
Get-Member is not for getting user's group membership. If you want to get a list of groups a user belongs to on the local system, you can do so by:
$query = "ASSOCIATORS OF {Win32_Account.Name='DemoUser1',Domain='DomainName'} WHERE ResultRole=GroupComponent ResultClass=Win32_Account"
Get-WMIObject -Query $query | Select Name
In the above query, replace DemoUser1 with the username you want and the DomainName with either your local computer name or domain name.
Get group membership for a user:
$strUserName = "Primoz"
$strUser = get-qaduser -SamAccountName $strUserName
$strUser.memberof
See Get Group Membership for a User
But also see Quest's Free PowerShell Commands for Active Directory.
[Edit: Get-ADPrincipalGroupMembership command is included in Powershell since v2 with Windows 2008 R2. See kstrauss' answer below.]
Get-Member is a cmdlet for listing the members of a .NET object. This has nothing to do with user/group membership. You can get the current user's group membership like so:
PS> [System.Security.Principal.WindowsIdentity]::GetCurrent().Groups |
Format-Table -auto
BinaryLength AccountDomainSid Value
------------ ---------------- -----
28 S-1-5-21-... S-1-5-21-2229937839-1383249143-3977914998-513
12 S-1-1-0
28 S-1-5-21-... S-1-5-21-2229937839-1383249143-3977914998-1010
28 S-1-5-21-... S-1-5-21-2229937839-1383249143-3977914998-1003
16 S-1-5-32-545
...
If you need access to arbitrary users' group info then #tiagoinu suggestion of using the Quest AD cmdlets is a better way to go.
I wrote a PowerShell function called Get-ADPrincipalGroupMembershipRecursive. It accepts the DSN of a user, computer, group, or service account. It retrieves an initial list of groups from the account's memberOf attribute, then recursively checks those group's memberships. Abbreviated code is below. Full source code with comments can be found here.
function Get-ADPrincipalGroupMembershipRecursive( ) {
Param(
[string] $dsn,
[array]$groups = #()
)
$obj = Get-ADObject $dsn -Properties memberOf
foreach( $groupDsn in $obj.memberOf ) {
$tmpGrp = Get-ADObject $groupDsn -Properties memberOf
if( ($groups | where { $_.DistinguishedName -eq $groupDsn }).Count -eq 0 ) {
$groups += $tmpGrp
$groups = Get-ADPrincipalGroupMembershipRecursive $groupDsn $groups
}
}
return $groups
}
# Simple Example of how to use the function
$username = Read-Host -Prompt "Enter a username"
$groups = Get-ADPrincipalGroupMembershipRecursive (Get-ADUser $username).DistinguishedName
$groups | Sort-Object -Property name | Format-Table
No need for long scripts when it is a simple one liner..
QUEST Command
(Get-QADUser -Identity john -IncludedProperties MemberOf | Select-Object MemberOf).MemberOf
MS AD Command
(GET-ADUSER –Identity john –Properties MemberOf | Select-Object MemberOf).MemberOf
I find the MS AD cmd is faster but some people like the Quest ones better..
Steve
Use:
Get-ADPrincipalGroupMembership username | select name | export-CSV username.csv
This pipes output of the command into a CSV file.
First, import the ActiveDirectory module:
Import-Module ActiveDirectory
Then issue this command:
Get-ADGroupMember -Identity $group | foreach-object {
Write-Host $_.SamAccountName
}
This will display the members of the specified group.
It is just one line:
(get-aduser joe.bloggs -properties *).memberof
end of :)
The below works well:
get-aduser $username -Properties memberof | select -expand memberof
If you have a list of users:
$list = 'administrator','testuser1','testuser2'
$list | `
%{
$user = $_;
get-aduser $user -Properties memberof | `
select -expand memberof | `
%{new-object PSObject -property #{User=$user;Group=$_;}} `
}
Get-QADUser -SamAccountName LoginID | % {$_.MemberOf } | Get-QADGroup | select name
Get-ADUser -Filter { memberOf -RecursiveMatch "CN=Administrators,CN=Builtin,DC=Fabrikam,DC=com" } -SearchBase "CN=Administrator,CN=Users,DC=Fabrikam,DC=com" -SearchScope Base
## NOTE: The above command will return the user object (Administrator in this case) if it finds a match recursively in memberOf attribute.
I couldn't get the following to work for a particular user:
Get-ADPrincipalGroupMembership username
It threw an error that I was not willing to troubleshoot.
I did however come up with a different solution using Get-ADUser. I like it a bit better because if you don't know the account name then you can get it based off of a wildcard on the user's actual name. Just fill in PartOfUsersName and away it goes.
#Get the groups that list of users are the member of using a wildcard search
[string]$UserNameLike = "*PartOfUsersName*" #Use * for wildcards here
[array]$AccountNames = $(Get-ADUser -Filter {Name -like $UserNameLike}).SamAccountName
ForEach ($AccountName In $AccountNames) {
Write-Host "`nGETTING GROUPS FOR" $AccountName.ToUpper() ":"
(Get-ADUser -Identity $AccountName -Properties MemberOf|select MemberOf).MemberOf|
Get-ADGroup|select Name|sort name
}
Huge props to schmeckendeugler and 8DH for getting me to this solution. +1 to both of you.
To get it recursive, you can use:
<#
.SYNOPSIS
Get all the groups that a user is MemberOf.
.DESCRIPTION
This script retrieves all the groups that a user is MemberOf in a recursive way.
.PARAMETER SamAccountName
The name of the user you want to check #>
Param (
[String]$SamAccountName = 'test',
$DomainUsersGroup = 'CN=Domain Users,CN=Users,DC=domain,DC=net'
)
Function Get-ADMemberOf {
Param (
[Parameter(ValueFromPipeline)]
[PSObject[]]$Group,
[String]$DomainUsersGroup = 'CN=Domain Users,CN=Users,DC=grouphc,DC=net'
)
Process {
foreach ($G in $Group) {
$G | Get-ADGroup | Select -ExpandProperty Name
Get-ADGroup $G -Properties MemberOf| Select-Object Memberof | ForEach-Object {
Get-ADMemberOf $_.Memberof
}
}
}
}
$Groups = Get-ADUser $SamAccountName -Properties MemberOf | Select-Object -ExpandProperty MemberOf
$Groups += $DomainUsersGroup
$Groups | Get-ADMemberOf | Select -Unique | Sort-Object
Studying all comments presented gave me a starting point (thanks for such) but left me with several unresolved issues. As result here is my answer. The code snippet provided does a little more than what is asked for but it provides helpful debugging info.
[array] $script:groupsdns = #()
function Get-ADPrincipalGroupMembershipRecursive()
{
Param( [string] $dn, [int] $level = 0, [array] $groups = #() )
#if(($groupsdns | where { $_.DistinguishedName -eq $dn }).Count -ne 0 ) { return $groups } # dependency on next statement
#$groupsdns += (Get-ADObject $dn -Properties MemberOf) # Get-ADObject cannot find an object with identity
if ($script:groupsdns.Contains($dn)) { return $groups }
$script:groupsdns += $dn
$mo = $Null
$mo = Get-ADObject $dn -Properties MemberOf # Get-ADObject cannot find an object with identity
$group = ($dn + " (" + $level.ToString())
if ($mo -eq $Null) { $group += "!" }
$group += ")"
$groups += $group
foreach( $groupdn in $mo.MemberOf )
{
$groups = Get-ADPrincipalGroupMembershipRecursive -dn $groupdn -level ($level+1) -groups $groups
}
if ($level -le 0)
{
$primarygroupdn = (Get-ADUser -Identity $dn -Properties PrimaryGroup).PrimaryGroup
$groups = Get-ADPrincipalGroupMembershipRecursive -dn $primarygroupdn -level ($level+1) -groups $groups
}
return $groups
}
$adusergroups = Get-ADPrincipalGroupMembershipRecursive -dn $aduser.DistinguishedName
$adusergroups | ft -AutoSize | `
Out-File -Width 512 Get-ADPrincipalGroupMembershipRecursive.txt #-Append #-Wrap # | Sort-Object -Property Name
When you do not have privileges to consult other member groups but you do have the privilege to consult group members, you can do the following to build a map of which user has access to which groups.
$groups = get-adgroup -Filter * | sort name | select Name
$users = #{}
foreach($group in $groups) {
$groupUsers = #()
$groupUsers = Get-ADGroupMember -Identity $group.Name | Select-Object SamAccountName
$groupUsers | % {
if(!$users.ContainsKey($_.SamAccountName)){
$users[$_.SamAccountName] = #()
}
($users[$_.SamAccountName]) += ($group.Name)
}
}
For LOCAL users and groups (ie not in Active Directory), and if you don't want to, or aren't allowed to, or can't install RSAT and/or Install-WindowsFeature RSAT-AD-PowerShell and/or import-module activedirectory then here's a pure, pre-installed powershell (5.1+) way to do it.
(Note: Get-LocalGroup* used below are only available Powershell v5.1 and above. "...v5.1 was released along with the Windows 10 Anniversary Update on August 2, 2016, and in Windows Server 2016. ...[F]or Windows 7, Windows Server 2008, Windows Server 2008 R2, Windows Server 2012, and Windows Server 2012 R2 [it] was released on January 19, 2017." (wikipedia))
$username = "user002"
Get-LocalGroup | ForEach-Object {
# the usernames are returned in the string form "computername\username"
if (Get-LocalGroupMember -Group $_ | Where-Object name -like "*\$username") {
$_.name
}
}
Example output:
Administrators
Users
Import-Module ActiveDirectory
Get-ADUser -SearchBase "OU=Users,DC=domain,DC=local" -Filter * | foreach-object {
write-host "User:" $_.Name -foreground green
Get-ADPrincipalGroupMembership $_.SamAccountName | foreach-object {
write-host "Member Of:" $_.name
}
}
Change the value of -SearchBase to reflect the OU you need to list the users from :)
This will list all of the users in that OU and show you which groups they are a member of.
Get-ADPrincipalGroupMembership USERLOGON | select name
This is the simplest way to just get the names:
Get-ADPrincipalGroupMembership "YourUserName"
# Returns
distinguishedName : CN=users,OU=test,DC=SomeWhere
GroupCategory : Security
GroupScope : Global
name : testGroup
objectClass : group
objectGUID : 2130ed49-24c4-4a17-88e6-dd4477d15a4c
SamAccountName : testGroup
SID : S-1-5-21-2114067515-1964795913-1973001494-71628
Add a select statement to trim the response or to get every user in an OU every group they are a user of:
foreach ($user in (get-aduser -SearchScope Subtree -SearchBase $oupath -filter * -Properties samaccountName, MemberOf | select samaccountName)){
Get-ADPrincipalGroupMembership $user.samaccountName | select name}
Almost all above solutions used the ActiveDirecotry module which might not be available by default in most cases.
I used below method. A bit indirect, but served my purpose.
List all available groups
Get-WmiObject -Class Win32_Group
And then list the groups the user belongs to
[System.Security.Principal.WindowsIdentity]::GetCurrent().Groups
Comparison can then be done via checking through the SIDs. This works for the logged in user. Please correct me if I am wrong. Completely new to PowerShell, but had to get this done for a work commitment.
With user input and fancy output formatting:
[CmdletBinding(SupportsShouldProcess=$True)]
Param(
[Parameter(Mandatory = $True)]
[String]$UserName
)
Import-Module ActiveDirectory
If ($UserName) {
$UserName = $UserName.ToUpper().Trim()
$Res = (Get-ADPrincipalGroupMembership $UserName | Measure-Object).Count
If ($Res -GT 0) {
Write-Output "`n"
Write-Output "$UserName AD Group Membership:"
Write-Output "==========================================================="
Get-ADPrincipalGroupMembership $UserName | Select-Object -Property Name, GroupScope, GroupCategory | Sort-Object -Property Name | FT -A
}
}
Putting this here for future reference. I'm in the midst of an email migration. I need to know each user account and its respective group membership, and also I need to know each group and its respective members.
I'm using the code block below to output a CSV for each user's group membership.
Get-ADUser -Filter * |`
ForEach-Object { `
$FileName = $_.SamAccountName + ".csv" ; `
$FileName ; `
Get-ADPrincipalGroupMembership $_ | `
Select-Object -Property SamAccountName, name, GroupScope, GroupCategory | `
Sort-Object -Property SamAccountName | `
Export-Csv -Path $FileName -Encoding ASCII ; `
}
The export process for the groups and their respective members was a little convoluted, but the below works. The output filenames include the type of group. Therefore, the email distribution groups I need are/should be the Universal and Global Distribution groups. I should be able to just delete or move the resulting TXT files I don't need.
Get-ADGroup -Filter * | `
Select-Object -Property Name, DistinguishedName, GroupScope, GroupCategory | `
Sort-Object -Property GroupScope, GroupCategory, Name | `
Export-Csv -Path ADGroupsNew.csv -Encoding ASCII
$MyCSV = Import-Csv -Path .\ADGroupsNew.csv -Encoding ASCII
$MyCSV | `
ForEach-Object { `
$FN = $_.GroupScope + ", " + $_.GroupCategory + ", " + $_.Name + ".txt" ; `
$FN ; `
Get-ADGroupMember -Identity $_.DistinguishedName | `
Out-File -FilePath $FN -Encoding ASCII ; $FN=""; `
}