Active Directory to CSV
# Import Active Directory module (if not already loaded)
Import-Module ActiveDirectory
# Replace 'YourGroupName' with the actual group name and 'YourPrefix' with the desired prefix
$groupName = "YourGroupName"
$prefix = "YourPrefix"
# Get members of the group
$groupMembers = Get-ADGroupMember -Identity $groupName -Recursive
# Loop through each member and retrieve details
$userInformation = foreach ($member in $groupMembers) {
# Get AD user object with necessary properties
$user = Get-ADUser -Identity $member.SamAccountName -Properties GivenName, Surname, Title, SamAccountName
# Check if user object is retrieved successfully (avoid errors)
if ($user) {
# Create an object with user details, including prefix
[pscustomobject]@{
Prefix = $prefix
FirstName = $user.GivenName
LastName = $user.Surname
Title = $user.Title
SamaccountName = $user.SamAccountName
}
} else {
# Handle case where user object couldn't be retrieved
Write-Warning "Failed to retrieve details for: $member.SamAccountName"
}
}
# Define the output file path (modify as needed)
$outputFile = "C:\Users\YourName\Desktop\GroupUsers.csv"
# Export the information to the CSV file
$userInformation | Export-Csv -Path $outputFile -NoTypeInformation