Home > Enterprise >  PowerShell script to query AD and report if UPNs in a CSV file are found
PowerShell script to query AD and report if UPNs in a CSV file are found

Time:11-03

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.

CodePudding user response:

You can either switch strategy to process them 1-by-1 - suppress the error from Get-ADUser with -ErrorAction SilentlyContinue and then use an if statement to test if anything was returned:

$CSVFile = Read-Host -Prompt 'Enter the name of the user CSV file (filename.csv)'
$Path = 'C:\scripts'
$UPNs = Import-Csv $Path\$CSVFile
foreach ($UPN in $UPNs.userprincipalname) {
    $UID = (Get-ADUser -Filter {UserPrincipalName -eq $UPN} -ErrorAction SilentlyContinue).SamAccountName
    if($UID){
        Remove-ADGroupMember "My-AD-Group" -Members $UIDs
    }
}

Alternative filter out any possible $null values from the $UIDs array before passing it to Remove-ADGroupMember:

Remove-ADGroupMember "My-AD-Group" -Members $UIDs.Where({$_})

CodePudding user response:

If you want to send a warning to the PS Host showing those UPNs which were not found and also skip null or white space elements on your CSV you could use:

$UIDs = Foreach ($UPN in $UPNs.userprincipalname)
{
    if([string]::IsNullOrWhiteSpace($UPN))
    {
        continue
    }

    if(-not($usr = Get-ADUser -LDAPFilter "(UserPrincipalName=$UPN)"))
    {
        Write-Warning "- Not Found: $UPN"
    }
    else
    {
        $usr.DistinguishedName
    }
}
Remove-ADGroupMember "My-AD-Group" -Members $UIDs
  • Related