Forum Discussion

Erik_Mullins's avatar
Erik_Mullins
Copper Contributor
Apr 19, 2021

Reading a text file for users to get-adprincipalgroupmembership

I would like to have powershell read a list of users (text file is fine) and perform 

Get-ADPrincipalGroupMembership UserName | Select Name
 for each user.  Ideally I would like this to be | Export-CSV with each user in its own column and groups listed underneath.  However I will take anything I can get at this point as long as I can tell what groups belong to which user.  I have tried Get-content and tried to pass that to an object or variable without any luck.  I hope you can assist me because I have a rather large project on my hands and this part of the project is slightly time consuming and I think PS can help but dont know how.

1 Reply

  • Seshadrr's avatar
    Seshadrr
    Iron Contributor

    ###########################################################
    # COMMENT: This script exports Active Directory users
    # membership with a certain attribute
    ###########################################################


    $path = Split-Path -parent "C:\ExportADUsers\*.*"

    $SearchBase = "OU=Ou1,DC=rs,DC=local"

    #Create a variable for the date stamp in the log file

    $LogDate = get-date -f yyyyMMddhhmm

    #Define CSV and log file location variables
    #they have to be on the same location as the script

    $csvfile = $path + "\AllUsers_$logDate.csv"

    #import the ActiveDirectory Module

    Import-Module ActiveDirectory

    get-aduser -filter * -Properties * -searchbase $SearchBase |

    Select-Object @{Label = "First Name";Expression = {$_.GivenName}},
    @{Label = "Last Name";Expression = {$_.Surname}},
    @{Label = "Display Name";Expression = {$_.DisplayName}},
    @{Label = "Logon Name";Expression = {$_.sAMAccountName}},
    @{n=’MemberOf’; e= { ( $_.memberof | % { (Get-ADObject $_).Name }) -join “,” }},
    @{Label = "distinguishedName";Expression = {$_.distinguishedName}},
    @{Label = "Email";Expression = {$_.Mail}},
    @{Label = "whenChanged";Expression = {$_.whenChanged}},
    @{Label = "Account Status";Expression = {if (($_.Enabled -eq 'TRUE') ) {'Enabled'} Else {'Disabled'}}}, # the 'if statement# replaces $_.Enabled
    @{Label = "userPrincipalName";Expression = {$_.userPrincipalName}} ,
    @{Label = "PasswordNeverExpires";Expression = {$_.PasswordNeverExpires}},
    @{Label = "Last LogOn Date";Expression = {$_.lastlogondate}} | Export-Csv -Path $csvfile -NoTypeInformation -Encoding Default

Resources