Skip to content

Instantly share code, notes, and snippets.

@cuongitl
Created November 8, 2024 07:03
Show Gist options
  • Select an option

  • Save cuongitl/6d95fb46c6ba8f8eb9b38b119ea1fec2 to your computer and use it in GitHub Desktop.

Select an option

Save cuongitl/6d95fb46c6ba8f8eb9b38b119ea1fec2 to your computer and use it in GitHub Desktop.
How to get all groups that a user is a member of?
# Set the username for which to fetch the groups
# Usage: Get-memberOf-User.ps1 <username>
param (
[string]$username
)
# If no username is provided, prompt the user for input
if (-not $username) {
Write-Host "Please provide a username as an argument."
exit
}
# Get the directory of the currently running script
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
# Set the output file path for CSV (same directory as script)
$outputPath_csv = Join-Path $scriptDir "output.csv"
# Get the user with their MemberOf attribute (groups)
$user = Get-ADUser -Identity $username -Properties MemberOf
# Extract the group names from the MemberOf attribute
$groupNames = $user.MemberOf | ForEach-Object {
# Extract just the group name from the Distinguished Name (DN)
(Get-ADGroup $_).Name
}
# Print the user and their groups to the console
Write-Host "User: $($user.SamAccountName)"
Write-Host "Groups:"
# Print each group name in a new line in the console
$groupNames | ForEach-Object { Write-Host $_ }
# If you want to display them in a single line (comma separated)
# Write-Host "Groups: $($groupNames -join ', ')"
# Prepare data to export to CSV
$exportData = [PSCustomObject]@{
UserName = $user.SamAccountName
FirstName = $user.GivenName
LastName = $user.Surname
Email = $user.EmailAddress
Groups = ($groupNames -join ", ") # Join group names into a single string
}
# Export the data to CSV
$exportData | Export-Csv -Path $outputPath_csv -NoTypeInformation
# Output the location of the exported CSV file
# Write-Host "Exported user and groups to $outputPath_csv"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment