How to list out multiple ADUsers with ADPrincipalGroupMembership?

I have question regarding ADuser. Totally appreciate your busy, would be really greatful if you point the best way to go about this.

Am trying to amalgamate get-aduser with ADprinciplegroupmembership using a variable for a list of names that ive already exported out to a Export-Csv file.

The aim here is display samaccountname followed by their respective group memberships and then piped to a further csv file.

Mu attempts keep resulting in errors whereby it displays errors around the variable $users am using as a placeholder of the -identity. Ive also tried wholesale with -filter *.

either way it results in error. i have reached a mental block. Am trying to kill 2 birds with one stone i guess

any help is greatly appreciated.

many thanks in advance

max
on $psversiontable 5.0

Max,
Welcome to the forum. :wave:t4:

You forgot to share your code. :wink:

When you post code, sample data, console output or error messages please format it as code using the preformatted text button ( </> ). Simply place your cursor on an empty line, click the button and paste your code.

Thanks in advance

How to format code in PowerShell.org <---- Click :point_up_2:t4: :wink:

Hello Olaf.

Thank you for the kind words.

Sorry about that, quiet right, might help If I include the code: :grin:

so basically at this stage am doing the following:

$users = Get-Content .\users.txt

foreach($user in $users){

write-host "Group Membership for: " $user

Get-ADPrincipalGroupMembership -Identity $user | Select name | ft -hidetableheaders| export-csv .\usersnameswithgrp.csv

Here is the error that appears:

Group Membership for:  Bob7             

Get-ADPrincipalGroupMembership : Cannot find an object with identity: 'Bob7             

' under: 'DC=ACME,DC=com'.

At line:4 char:1

+ Get-ADPrincipalGroupMembership -Identity $user | Select name | ft -hi ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : ObjectNotFound: (Bob7              :ADPrincipal) [Get-ADPr

   incipalGroupMembership], ADIdentityNotFoundException

    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.A

   DIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADPrincipa 

  lGroupMembership

And here is the snippet of the resulting CSV file that gets created: -As you will see it does not display all the goups name (is this a permissions related issue?)


#TYPE System.Management.Automation.PSCustomObject

UserName

GroupName

GroupSamAccountname

Domain Users

Domain Users

samaccountname     

Domain Users

Domain Users

--------------     

Domain Users

Domain Users

Administrator      

Domain Users

Domain Users

Bob 1

Domain Users

Domain Users

Bob 2

Domain Users

Domain Users

Bob 3

Domain Users

Domain Users

Bob 4

Domain Users

Domain Users

Bob 5

Domain Users

Domain Users

So whislt it does error, it does produce the file but the contents do not display the various groups for the user that I can ordinarily see for individual user when using their name explicitly after the ‘Get-ADPrincicpalGroupMembership’ -identity Bob6 -all am getting is Domain User :unamused:

Im just trying to reel of users with their respective ‘Get-ADPrincipalGroupMembership’ Ive different versions but it often dont like the variable used a the parameter for -identity.

I didnt think it should be this difficult to achieve.

Any help would be appreciated…Many Thanks in advance…

Max

I’m afraid you have some misconceptions about PowerShell and how to work with it in your head. :wink: You may do a step back and start with learning the very basics of PowerShell first. :+1:t4:

Format cmdlets like Format-Table are meant to be used for console output only. In the vast majority of the cases it does not make any sense to pipe their output to any other cmdlet. So they should always be the last cmdlet in a pipeline.

If you use Export-Csv inside a loop and you don’t use the parameter -Append each loop iteration overwrites the CSV file with the new content.

Depending on what you want to do with the output you have several options how to output the results of your queries. I’d recommend to use a nested loop with a [PSCUstomObject] in it. This way you can easily use the result in any further process.

$UserList = Get-Content -Path .\users.txt
$ResultList = 
foreach ($User in $UserList) {
    $MemberShipList = Get-ADPrincipalGroupMembership -Identity $User
    foreach ($MemberShip in $MemberShipList) {
        [PSCustomObject]@{
            Name      = $User
            GroupName = $MemberShip.name
            GroupDN   = $MemberShip.distinguishedName
        }
    }
}
$ResultList

$ResultList |
Export-Csv -Path .\usersnameswithgrp.csv -NoTypeInformation
1 Like

Hi Olaf,

I tried the suggested cmdlet/script as suggested and it results in:

![image|690x270](upload://8mpoqxjhjQKG6Jgr7qfJpdrUvM3.png)



It still does not display the name of the groups.

With regards to taking step back, well tbh honest Im revsiting the PS scripting after a long whi,le and just needed to be nudged in the right direction on it. I appreciate format-tables are not necessary for exports, it was just in there when I copied from online.:blush:

I mean what would you suggest as for the distinguished name it just displays: ‘Microsoft.ActiveDirectory.Management.ADPropertyValueCollection’.

![image|690x270](upload://cWyGPkfMXPaYne3o9xM5GTHYWrk.png)

Many Thanks
Max

OK, I had a typo in the [PSCustomObject] for the DistinguishedName - I just corrected my code suggestion above - but the rest of the code works as expected. I just tested it.

The images you seemingly wanted to upload do not show. You may rather post the plain text instead anyway and format it as code.

What do you have in your input file?

Not sure what the typo is at [PSCustomObject] as it appears to be spelt OK on mine.
The attempted upload was the results from the script, as below:

Name                 GroupName    GroupDN                                         

----                 ---------    -------                                         

                     Domain Users CN=Domain Users,CN=Users,DC=somecompany,DC=com

samaccountname       Domain Users CN=Domain Users,CN=Users,DC=somecompany,DC=com

--------------       Domain Users CN=Domain Users,CN=Users,DC=somecompany,DC=com

Administrator        Domain Users CN=Domain Users,CN=Users,DC=somecompany,DC=com

Bob1                Domain Users CN=Domain Users,CN=Users,DC=somecompany,DC=com

Bob2                Domain Users CN=Domain Users,CN=Users,DC=somecompany,DC=com

Bob3                Domain Users CN=Domain Users,CN=Users,DC=somecompany,DC=com

Bob4                Domain Users CN=Domain Users,CN=Users,DC=somecompany,DC=com

Bob5                Domain Users CN=Domain Users,CN=Users,DC=somecompany,DC=com

Bob6                 Domain Users CN=Domain Users,CN=Users,DC=somecompany,DC=com

Bob7                Domain Users CN=Domain Users,CN=Users,DC=somecompany,DC=com

Bob8                Domain Users CN=Domain Users,CN=Users,DC=somecompany,DC=com

Bob9                 Domain Users CN=Domain Users,CN=Users,DC=somecompany,DC=com

so as you can see it does not display the individual group names, they users belong to.

The input file, Its simply a notepad file with a list of names (so string), that part of it works.

Your thougts…. (I mean could a lack permissions be the problem?)

Many Thanks
Max

First I had DisinguishedName instead of DistinguishedName. But as I said I corrected it. :wink:

I don’t know what to advice. The code works in my environment as expected.

Your output looks weird. First of all that you have empty lines in between each result line. Then an empty name at the start and a name with “-------------”.

Instead of using an input file I’d try to use a limitted set of users where you definitely know that they have more than one groupmembership. Like this:

$UserList = 'User_One', 'User_Two'

And your input file should have ONLY valid sAMAccountNames, DistinguishedNames, GUIDs or SIDs - nothing else - no empty lines - no headers - no formats - N O T H I N G !! :point_up_2:t4:

Usually not if you just read infromation from the AD. Try to run the commands individually and inspect the output.

Hello Olaf.

To be honest Ithasnt copied across very well. but the line “------------” is not a user name, its actually part of the column header.

Yes I think I need to breakdown the adprinciapalgroupmembers process down a little further, and try it in the way you described -Thanks for the advice anyway…

Will let you know what happens.

Have a goods Xmas breakanyway,

Hi Olaf,

coming back to this, hoping you had a good xmas break and a good new year.

So I attempted as you suggested by explicitly entering in the names in to the variable like:
Preformatted text $UserList = ‘User_One’, 'User_Two’Preformatted text

That works and worked perfectly fine, but I want to be able to have the same affect from a CSV or filename with the similar contents either through a .Txt file or CSV.

How can this be done because every time I do it as a variable the error of sytemobject …cant convert blah blah… I want to be able to have be read into the variable via the get-content…

it only appears to be failing at the point of the ‘-identity’ parameter where I been putting in the variable.

Your kind thoughts or help on this would be helpful.

Many Thanks
Max

Please share the (exact but from sensitive information sanitized) code you’re using, show a few lines of a sample input file (also exact but sanitized from sensitive information) AND the complete error message you get - all formatted as code please.