UserName,GroupName
User1,Group1
User2,Group1
User3,Group2
User4,Group2
# Import the CSV file
$CSVPath = "C:\Path\To\Members.csv"
$Members = Import-Csv -Path $CSVPath
# Define the output file
$OutputPath = "C:\Path\To\Result.csv"
$Results = @() # Array to store results
# Loop through each row in the CSV
foreach ($Member in $Members) {
$UserName = $Member.UserName
$GroupName = $Member.GroupName
# Try to add the user to the group
try {
Add-ADGroupMember -Identity $GroupName -Members $UserName -ErrorAction Stop
# Log success
$Results += [PSCustomObject]@{
UserName = $UserName
GroupName = $GroupName
Status = "Success"
Message = "User added successfully."
}
} catch {
# Log failure
$Results += [PSCustomObject]@{
UserName = $UserName
GroupName = $GroupName
Status = "Failure"
Message = $_.Exception.Message
}
}
}
# Export results to a CSV file
$Results | Export-Csv -Path $OutputPath -NoTypeInformation -Force
Write-Host "Operation completed. Results saved to $OutputPath" -ForegroundColor Cyan