Public/Check-UserGroupMembership.ps1

<#
.SYNOPSIS
    Checks if a user or users from a specified file are members of a specified Active Directory group.
 
.DESCRIPTION
    The Check-UserGroupMembership function retrieves the local site's domain controller,
    discovers the target global catalog, and checks if a single user or users listed in a provided
    text or CSV file are members of a specified group.
 
.PARAMETER GroupName
    The name of the Active Directory group to check membership against.
 
.PARAMETER UserInput
    A single username (sAMAccountName) or a path to a file containing usernames. If a file, specify
    the type with UserInputType.
 
.PARAMETER UserInputType
    Specifies the type of UserInput: 'Single' for a single username, 'TextFile' for a plain text file,
    or 'CSV' for a CSV file. Default is 'Single'.
 
.EXAMPLE
    PS> Check-UserGroupMembership -GroupName "ctx_xd7_win10_prod" -UserInput "jdoe"
 
    Checks if the user 'jdoe' is a member of the 'ctx_xd7_win10_prod' group.
 
.EXAMPLE
    PS> Check-UserGroupMembership -GroupName "ctx_xd7_win10_prod" -UserInput "C:\Users\list.txt" -UserInputType "TextFile"
 
    Checks each user in 'list.txt' to see if they are a member of the 'ctx_xd7_win10_prod' group.
 
.EXAMPLE
    PS> Check-UserGroupMembership -GroupName "ctx_xd7_win10_prod" -UserInput "C:\Users\list.csv" -UserInputType "CSV"
 
    Checks each user in 'list.csv' to see if they are a member of the 'ctx_xd7_win10_prod' group. Assumes usernames are listed under a column named 'Username'.
 
.NOTES
    Requires Active Directory module for PowerShell and appropriate permissions to query AD objects.
#>


Function Check-UserGroupMembership {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)]
        [string]$GroupName,

        [Parameter(Mandatory = $true)]
        [string]$UserInput,

        [Parameter(Mandatory = $false)]
        [ValidateSet("Single", "TextFile", "CSV")]
        [string]$UserInputType = "Single"
    )

    Begin {
        # Use the Global Catalog from the forest root domain
        try {
            $LocalSite = (Get-ADDomainController -Discover).Site
            $NewTargetGC = Get-ADDomainController -Discover -Service 6 -SiteName $LocalSite
            If (!$NewTargetGC) { $NewTargetGC = Get-ADDomainController -Discover -Service 6 -NextClosestSite }
            $GlobalCatalog = $($NewTargetGC.HostName) + ":3268"
            $Group = Get-ADGroup -Filter "Name -eq '$GroupName'" -Properties DistinguishedName, CanonicalName -Server $GlobalCatalog
            $GroupNameDN = $Group.DistinguishedName
        } catch {
            Write-Error "Failed to connect to the global catalog or retrieve group information: $_"
            return
        }
    }
    
    Process {
        switch ($UserInputType) {
            'Single' { $usernames = @($UserInput) }
            'TextFile' { $usernames = Get-Content -Path $UserInput }
            'CSV' { $usernames = Import-Csv -Path $UserInput | ForEach-Object { $_.Username } }
        }

        foreach ($username in $usernames) {
            try {
                $userDomain = (Get-ADUser -Filter {SamAccountName -eq $username} -Server $GlobalCatalog -Properties UserPrincipalName).DistinguishedName
                $userDC = ($userDomain -split ',' | Where-Object { $_ -like 'DC=*' } | ForEach-Object { $_.Substring(3) }) -join '.'

                $user = Get-ADUser -Identity $username -Properties MemberOf -Server $userDC
                $isMember = $user.MemberOf -contains $GroupNameDN
                Write-Output "$isMember"
            } catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
                Write-Warning "User '$username' not found in any domain within the forest."
            } catch {
                Write-Error "An unexpected error occurred while checking membership for '$username': $_"
            }
        }
    }
}