Copy group membership from one user to another in AD - powershell

Im tyring to build a script which will copy group memberships from one user to another in AD. Im trying to use powershell to automate this task. However im stuck while creating a check for the user. In other words when i copy group membership from one user to another i want to be able to run a check to see if the user is already a member of the group before adding them, bu doing this i can avoid errors which such as " this user is already a member of the group and cannot be added again" Any help or advice would be appreciated. Im using the following to script at the moment.
$copy = Read-host "Enter user to copy from"
$Sam = Read-host " Enter user to copy to"
Function Copymembership {
$members = Get-ADUser -Identity $copyp -Properties memberof
foreach ($groups in $members.memberof){
if ($members -notcontains $groups.sAMAccountname)
{Add-ADGroupMember -Identity $groups -Member $sam -ErrorAction SilentlyContinue
Write-Output $groups}
}
}
copymembership

Use Get-ADUser for both users. Then use the -notcontains operator to filter groups.
$CopyFromUser = Get-ADUser JSmith -prop MemberOf
$CopyToUser = Get-ADUser MAdams -prop MemberOf
$CopyFromUser.MemberOf | Where{$CopyToUser.MemberOf -notcontains $_} | Add-ADGroupMember -Member $CopyToUser

One line to get what the user member of.
Get-ADUser -Identity alan0 -Properties memberof | Select-Object -ExpandProperty memberof
One line to copy the membership from one user to another.
Get-ADUser -Identity <UserID> -Properties memberof | Select-Object -ExpandProperty memberof | Add-ADGroupMember -Members <New UserID>

Your code is too complicated for this idea. Not sure if it can be done without the import-Module AciveDirectory cmdlet.
It is much easer to do that when you import the ActiveDirectory tool and use the built-in cmdlet. Check my code:
# import the Active Directory module in order to be able to use get-ADuser and Add-AdGroupMembe cmdlet
import-Module ActiveDirectory
# enter login name of the first user
$copy = Read-host "Enter username to copy from: "
# enter login name of the second user
$paste = Read-host "Enter username to copy to: "
# copy-paste process. Get-ADuser membership | then selecting membership | and add it to the second user
get-ADuser -identity $copy -properties memberof | select-object memberof -expandproperty memberof | Add-AdGroupMember -Members $paste

Something like this should tell you if a group contains a specific member:
If ((Get-ADGroup "Domain Admins" -Properties Members).Members -Contains (Get-ADUser "AdminBob").DistinguishedName) {write-host "Yes"}
There might be something simpler but this was the first thing that came to mind.

param
(
[Parameter(Mandatory=$true)][string]$CopyFromUser,
[Parameter(Mandatory=$true)][string]$CopyToUser
)
$FromUserGroups = (Get-ADUser $CopyFromUser -Properties MemberOf).MemberOf
$CopyToUser = Get-ADUser $CopyToUser -Properties MemberOf
$FromUserGroups | Add-ADGroupMember -Members $CopyToUser

In case you want to have manual control on what groups are added, then this is perfect example for Out-GridView. Procedure is the same as explained by TheMadTechnician above, just before passing it to Add-ADGroupMember, you insert Out-GridView. You can even include group descriptions or other parameters.
$CopyFromUser = Get-ADUser JSmith -prop MemberOf
$CopyToUser = Get-ADUser MAdams -prop MemberOf
$MissingGroups = Compare-Object $CopyFromUser $CopyToUser -Property MemberOf | ? SideIndicator -eq '<='
$GroupsObj = $MissingGroups.MemberOf | Get-ADGroup –prop Description | Select Name,Description
$GroupsObj | Out-GridView -PassThru | Add-ADGroupMember -Member $CopyToUser

am trying build script to Copy group membership from one user to another in AD
i have one domain and 3 different subdomains, can you please check if there is anything in the script must be changed, because it doesn't work thanks
$From = Read-Host -Prompt "From User"
$to = Read-Host -Prompt "To User"
$CopyFromUser = Get-ADUser -Server "de.isringhausen.net" -Identity $From -Properties MemberOf
$Group = $CopyFromUser.MemberOf
$confirmation = Read-Host "Do you want to Copy Group Membership from $From to $to ? Press 'y' to Proceed or any key to Cancel"
if ($confirmation -eq 'y') {
$Group | Add-ADGroupMember -Members $to
clear
echo "($From) User's Group Memership has been Copied to User ($to)"
Pause
}
else {
Write-Host 'Task Cancelled'
}

Related

Faster Way to remove users from a huge list of groups?

I run the following code to remove disabled users from a list of 9874 groups:
$user = get-aduser <userid> -Server "<server from another domain>"
foreach ($Group in $Groups) {
Write-Host "Removing $user from $group" -Foreground Green
Remove-ADGroupMember -Identity $group -Members $user -Confirm:$false
}
It's a bottle neck for me as it checks/removes the account from each group. Is there a way to speed this up with more efficient PS code?
If memberOf is the only thing are you interested in for a given user, you can run the following. It only loads the memberOf property and removes the user from each of these. Gives you a bit of a performance boost since its not loading all the account properties.
Get-ADUser <userid> -Server "<server from another domain>" -Properties MemberOf `
| Select -Expand MemberOf | % {
Remove-ADGroupMember $_ -member <userid>"
}

How to remove All Groups with Exceptions by using Powershell?

I've seen many examples of using PS to remove all memberships (including Primary). I have working code as follows:
get-aduser person -properties MemberOf | Select -Expand MemberOf | %{Remove-ADGroupMember $_ -member person -confirm:$false}
This is great for stripping everything out, excluding Domain Users. No problems so far.
The next challenge is leaving behind a specific group, such as licensing for O365.
I attempted to build an array with exclusions, and excluding those from the removal:
$user = person
$keep = #(
'CN=nametokeep,OU=group,DC=company,DC=com',
'CN=nametoalsokeep,OU=group,DC=company,DC=com')
$groups = get-aduser person -properties memberof | select -expand memberof
$groups | %{$keep -notcontains $_} | Remove-ADGroupMember -member $user
The idea here is to define the exceptions and remove everything else that doesn't match up.
When I do this, the code does execute but prompts for input:
Members[0]:
Doesn't matter what value I put in there, the code just prompts again with Members[1], Members[2] and so on.
What am I missing?
In order to remove "person" from all the groups not in the keep array, you will need to do a Foreach on each of the groups out of the $keep array so you iterate through them.
Also, Remove-ADGroupMember does not have a -Member parameter.
Parameter is -Members and that's what your powershell prompt is asking about when you run the cmdlet without it's mandatory parameter.
The following script should accomplish what you seek.
$user = 'Person'
$keep = #(
'CN=nametokeep,OU=group,DC=company,DC=com',
'CN=nametoalsokeep,OU=group,DC=company,DC=com'
)
$groups = get-aduser -Identity $user -properties memberof | select -expand memberof
$groups.Where({$_ -notin ($keep)}) |
% { Remove-ADGroupMember -Identity $_ -Members $user}
Reference
Remove-ADGroupMember

PowerShell script runs with error first time, but correctly second or third time

I have a script to disable users in AD with the following steps:
asks for username
set "domain users" group as primary group
disable users in AD
move to disabled OU
clear Manager from AD
remove all groups except 'domain users'
Add disabled_mailboxes to the user
Hide account from exchande list
Now, when i try the first time it does not work. i have to run it several times like 2 3 and 4 times to work.
When i run it step by step, it work fine also from the first time
and here is the script:
$username = Read-Host -Prompt 'Enter Username'
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
Import-Module ActiveDirectory
$user = Get-ADUser -Filter {(SamAccountName -eq $username)} -Properties MemberOf
#set "domain users" group as primary group
$group = get-adgroup "Domain Users" -properties #("primaryGroupToken")
get-aduser $username | set-aduser -replace #{primaryGroupID=$group.primaryGroupToken}
#disable users in AD
Get-ADUser -Filter {(SamAccountName -eq $username)} | Disable-ADAccount -ErrorAction SilentlyContinue
#move to disabled OU
Get-ADUser -Filter {(SamAccountName -eq $username)} | Move-ADObject –TargetPath “OU=Users,OU=Disabled Objects,DC=xxxxxxx,DC=xxx,DC=XXX”
#clear Manager from AD
Get-ADUser -Filter {(SamAccountName -eq $username)} | Set-ADUser -Clear manager
#-------------------------
#remove all groups except 'domain users'
Get-ADPrincipalGroupMembership -Identity $username | % {Remove-ADPrincipalGroupMembership -Identity $username -MemberOf $_ -Confirm:$false -ErrorAction SilentlyContinue}
#code can be removed.
#$group = $user | Select-Object -ExpandProperty MemberOf
#Remove-ADGroupMember -Identity $group -Members $user.SamAccountName -Confirm:$false -ErrorAction SilentlyContinue
#-------------------------
#Add disabled_mailboxes to the user
Add-ADGroupMember -Identity 'disabled_mailboxes' -Member $User.SamAccountName -ErrorAction SilentlyContinue
#-------------------------
#Hide account from exchande list
Set-Mailbox -identity $user.SamAccountName -HiddenFromAddressListsEnabled $true -ErrorAction SilentlyContinue
Windows 2012R2, Exchange 2010
Can anyone help with that???
Thanks
Mina
Do not use Get-ADUser repeatedly in the sequential lines. Just use the existing $user variable that you've just populated with values. Most likely you are hitting an issue that Get-ADUser returns old cached value for DN right after you run Move-ADObject (this changes the DN of the user), and since all queries use DN to locate the user, you get the error. The second run has the target user already in the destination OU, so no errors arise.

Update Active Directory "mail" attribute via PowerShell

I'm trying to update the email address listed in AD for all the users in a particular OU. This is the powershell script I'm using, but it's not working properly
Import-Module ActiveDirectory
Get-ADUser -Filter * -SearchBase "OU=OtherOU,OU=SomeOu,DC=Domain,DC=local" | Set-ADUser -email $_.samaccountname#domain.com
I think it's because $_.samaccountname isn't returning anything when I try to do Set-ADUser.
Can anyone point me in the right direction for fixing this? Thanks!
Create a csv file with SamAccountName & email address
"SamAccountName","EmailAddress"
"john","john#xyz.com"
step 1: import to a variable
$users = Import-Csv .\email.csv
step 2: Call the variable
foreach ($user in $users) {
Set-ADUser -Identity $user.SamAccountName -EmailAddress $user.EmailAddress
}
In the current context $_ is null. You need to use Foreach-Object in order for $_ to be available.
Get-ADUser -Filter * ... | Foreach-Object{
Set-ADUser -Identity $_ -Email "$($_.samaccountname)#domain.com"
}
I suspect you'll need to use a subexpression for that:
"$($_.samaccountname)#domain.com"
Assuming username is domain\user1 or user1#domain.com
$user = "user1"
Set-ADUser $user -emailaddress "firtname.lastname#xyz.com"
Get-ADUser -Identity $user -Properties emailaddress
Get-ADUser -Filter * -SearchScope Subtree -SearchBase "OU=OUName,DC=domain,DC=com" |
Foreach-Object { Set-ADUser -Identity $_ -Email "$($_.samaccountname)#domain.com" }
This is from:
https://social.technet.microsoft.com/wiki/contents/articles/33311.powershell-update-mail-and-mailnickname-for-all-users-in-ou.aspx

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=""; `
}