How to List All Groups a User Belongs to with PowerShell

In the rapidly evolving landscape of IT, effective user management and understanding user roles remain critical for the security and efficiency of any organization. Among the tools available to IT professionals, PowerShell scripts stand out as powerful solutions for automating tasks. One such script is focused on listing all groups a user belongs to.

Background

User group memberships define the rights and permissions a user has within a network. As an organization grows, keeping track of these memberships becomes increasingly important. Yet, it can be cumbersome and prone to errors if done manually. This is where our PowerShell script shines. Specifically designed to list all groups a user is a member of, this script is invaluable for IT professionals and Managed Service Providers (MSPs). Ensuring correct group membership helps avoid privilege over-allocation and underpins an organization’s security posture.

The Script


#Requires -Version 4.0 -RunAsAdministrator

<#
.SYNOPSIS
    This will output the groups that the specified user belongs to.
.DESCRIPTION
    This will output the groups that the specified user belongs to.
.EXAMPLE
     -UserName "Administrator" -IsDomainUser
    Will get the groups that the user Administrator belongs to in Active Directory.
.EXAMPLE
     -UserName "Administrator"
    Will get the groups that the user Administrator belongs to on the machine it runs on.
.EXAMPLE
    PS C:> Get-User-Membership.ps1 -UserName "Administrator"
    Will get the groups that the user Administrator belongs to on the machine it runs on.
.OUTPUTS
    Output (PSCustomObject)
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2012
    If you wish to interact with AD you will need to install RSAT with at least the AD feature.
    Release Notes:
    Initial Release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
.COMPONENT
    ManageUsers
#>

[CmdletBinding()]
param (
    # Specify one user
    [Parameter(Mandatory = $false)]
    [String]
    $UserName,
    # Modify Local User Membership
    [Parameter(Mandatory = $false)]
    [Switch]
    $IsDomainUser
)

begin {}

process {
    if (-not $IsDomainUser) {
        # Get local machine groups
        Get-LocalGroup | ForEach-Object {
            $Group = $_.Name
            # Get users in current group
            # Check that $UserName is a member of this current group and output it to StdOut/Write-Output
            Get-LocalGroupMember -Group $Group | Where-Object { $_.Name -like "*$UserName" } | ForEach-Object {
                [PSCustomObject]@{
                    Group = $Group
                    User  = $_.Name
                }
            }
        }
    }
    else {
        if ((Get-Module -Name ActiveDirectory -ListAvailable -ErrorAction SilentlyContinue)) {
            try {
                Import-Module -Name ActiveDirectory
                # Get most of our data needed for the logic, and to reduce the number of time we need to talk to AD
                $ADUser = (Get-ADUser -Identity $UserName -Properties SamAccountName -ErrorAction SilentlyContinue).SamAccountName
            }
            catch {
                Write-Error -Message "Ninja Agent could not access AD, either RSAT was not installed or that the agent does not have permissions to view users and groups."
                exit 5 # Access Denied exit code
            }
            # Get a list of groups that the user is in
            # Loop through each group
            Get-ADGroup -Filter * -ErrorAction SilentlyContinue | ForEach-Object {
                $ADGroup = $_
                # Get users from current group and filter out all other users
                Get-ADGroupMember -Identity $ADGroup -ErrorAction SilentlyContinue | Where-Object {
                    $_.SamAccountName -like $ADUser
                } | ForEach-Object {
                    # Write out to StandardOutput
                    [PSCustomObject]@{
                        Group = $ADGroup.Name
                        User  = $_.SamAccountName
                    }
                }
            }
        }
        else {
            # Throw error that RSAT: ActiveDirectory isn't installed
            Write-Error -Message "RSAT: ActiveDirectory is not installed or not found on this computer. The PowerShell Module called ActiveDirectory is needed to proceed." -RecommendedAction "https://docs.microsoft.com/en-us/powershell/module/activedirectory/"
            exit 2 # File Not Found exit code
        }
    }
}
end {}

 

Access 300+ scripts in the NinjaOne Dojo

Get Access

Detailed Breakdown

The script can be divided into two primary components based on its function:

  • Local Group Membership Check: If the -IsDomainUser switch isn’t specified, the script fetches and lists groups the specified user is a member of on the local machine.
  • Active Directory Group Membership Check: If the -IsDomainUser switch is set, the script communicates with the Active Directory to fetch and list the groups the specified user is a part of.

Throughout the process, the script outputs the results as a PSCustomObject, ensuring that the data is structured and can be easily understood or processed further.

Potential Use Case

Imagine an IT professional at a large enterprise who needs to verify the group memberships of a new department head. Using the script, the IT professional can easily list all groups the user is a member of in both local and Active Directory environments. This ensures the department head has the correct permissions, avoiding potential security breaches or access errors.

Alternative Approach

While the graphical interface of Active Directory Users and Computers (ADUC) allows viewing of group memberships, it’s manual and not suitable for bulk checks. Our PowerShell script automates this task, making it efficient for checking multiple users or frequent audits. Moreover, with PowerShell, results can be easily exported, filtered, or integrated into reports, offering flexibility that GUI tools lack.

FAQs

  • Q: Can the script be run without administrator privileges?
    A: The script requires administrative rights, ensuring accurate results by accessing necessary system resources.
  • Q: What if the Active Directory module isn’t found on the system?
    A: The script will throw an error, advising the installation of RSAT with the Active Directory feature.

Implications

Incorrect group memberships can lead to unauthorized data access or denial of essential resources to users. By accurately determining user memberships using our PowerShell script, IT professionals can enhance security and ensure regulatory compliance.

Recommendations

  • Always run the script in a safe and controlled environment first.
  • Regularly audit user group memberships, especially for high-privilege roles.
  • Integrate the script results into a broader IAM (Identity and Access Management) strategy.

Final Thoughts

NinjaOne, with its comprehensive suite of IT solutions, can be an invaluable partner in automating, managing, and securing IT environments. When scripts like the one discussed above are combined with the capabilities of NinjaOne, IT professionals can enhance their efficiency, accuracy, and security posture. This synergy paves the way for a proactive approach to IT management and security.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).