I have a simple script that references a CSV file containing user account UPNs and then removes these users from an AD group.
$CSVFile = Read-Host -Prompt 'Enter the name of the user CSV file (filename.csv)'
$Path = 'C:\scripts'
$UPNs = Import-Csv $Path\$CSVFile
$UIDs = Foreach ($UPN in $UPNs.userprincipalname) {
(Get-Aduser -filter {UserPrincipalName -eq $UPN}).SamAccountName
}
Remove-ADGroupMember "My-AD-Group" -Members $UIDs
The problem is that if the CSV file contains a UPN that isn't in AD, it will fail and give an error referencing that "Members" cannot be a null value. Once I remove the invalid UPN the script will work fine. I would like to add a kind of error check that goes through the UPNs and if one is not found in AD, it won't abort the entire function. I would like it to give an output with a list of the UPNs that couldn't be matched in AD. Thank you in advance for any suggestions.