The Export-CSV expects to receive an object with named properties, not a simple string value. See if this works for you:
# Replace the path with the actual location of your CSV file
$csvPath = "C:\Testuser.csv"
# Specify the three target groups (replace with your desired group names)
$group1 = "Group1"
$group2 = "Group2"
$group3 = "Group3"
# Import the CSV and iterate through each user
$TheData = @{UPN="";Result=""}
Import-Csv $csvPath | ForEach-Object {
$userUPN = $_.Username
$TheData.UPN = $_.Username
try {
# Check if the user account exists in Active Directory
$adUser = Get-ADUser -Filter "UserPrincipalName -eq '$userUPN'" -ErrorAction Stop -Properties Enabled, MemberOf
# Check if the user is enabled
if ($adUser.Enabled) {
# Check if the user is a member of at least one of the target groups
if ($adUser.MemberOf -like "*$group1*" -or
$adUser.MemberOf -like "*$group2*" -or
$adUser.MemberOf -like "*$group3*") {
$theData.Result = "Criteria matches (User is enabled and in at least one of the specified groups)."
# Write-Output "{$userUPN}: Criteria matches (User is enabled and in at least one of the specified groups)."
} else {
$TheData.Result = "Criteria doesn't match (User is enabled but not in any of the specified groups)."
# Write-Output "{$userUPN}: Criteria doesn't match (User is enabled but not in any of the specified groups)."
}
} else {
$TheData.Result ="Criteria doesn't match (User account is disabled)."
# Write-Output "{$userUPN}: Criteria doesn't match (User account is disabled)."
}
} catch {
$TheData.Result ="{$userUPN}: AD account not found."
# Write-Output "{$userUPN}: AD account not found."
}
[PSCustomObject]$TheData
} | Export-Csv -Path "C:\Results.csv" -NoTypeInformation
I left the original "Write-Output" cmdlets in the code, but turned them into comments.