Getting users by their DisplayName property is not the safest thing to do. It would be so much better if your CSV file has other, more unique properties to go by, like SamAccountName, UserPrincipalName, DistinguishedName or EmailAddress..
Anyway, in your loop, you should check if a user with that name can be found and only if so, get the group membership.
Import-Csv 'C:\Users.csv' | ForEach-Object { $user = Get-ADUser -Filter "DisplayName -eq '$($_.username)'" -Properties DisplayName if ($user) { Get-ADprincipalGroupMembership -Identity $user.DistinguishedName | Where-Object { $_.name -like 'SSL_VPN*' } | Select-Object @{ Name = 'SamAccountName'; Expression = { $user.SamAccountName } }, @{ Name = 'Group'; Expression = { $_.name }} } else { Write-Warning "User '$($_.username)' not found" # if you want this message to also appear in your output CSV, do something like this: [PsCustomObject]@{ 'SamAccountName' = "User '$($_.username)' not found" 'Group' = '' } } } | Export-Csv -Path 'C:\UserPermiss.csv' -NoTypeInformation
If you want to see a warning message when the user is not a member of the SSL_VPN group, you can do:
Import-Csv 'C:\Users.csv' | ForEach-Object { $user = Get-ADUser -Filter "DisplayName -eq '$($_.username)'" -Properties DisplayName if ($user) { $group = Get-ADprincipalGroupMembership -Identity $user.DistinguishedName | Where-Object { $_.name -like 'SSL_VPN*' } if ($group) { [PsCustomObject]@{ 'SamAccountName' = $user.SamAccountName 'Group' = $group.name } } else { Write-Warning "User '$($_.username)' is not a member of ssl_vpn group" } } else { Write-Warning "User '$($_.username)' not found" } } | Export-Csv -Path 'C:\UserPermiss.csv' -NoTypeInformation
Get-ADPrincipalGroupMembership | Where Name -like 'SSL_VPN*'do what you need? It is hard to tell if your issues are filtering for the groups or outputting in the proper format in the CSV.