PowerShell Add AD users to AD group by UPN from CSV

Import-CSV "C:\Temp\jacktest.csv" | Foreach-Object {
  $aduser = Get-ADUser -Filter "UPN-eq '$($_.UPN)'"
  if( $aduser ) {
    Write-Output "Adding user $($aduser.SamAccountName) to groupname"
    Add-ADGroupMember -Identity JackTest -Members $aduser
  } else {
    Write-Warning "Could not find user in AD with email address $($_.EmailAddress)"
  }
}

I receive the following Error:

Transcript started, output file is C:\Temp\Add-ADUsers.log Get-ADUser : The search filter cannot be recognized At line:19 char:15

  • $ADUser = Get-ADUser -Filter "UPN -eq '$UPN'" | Select-Object Sam ...
    
  •           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException
    • FullyQualifiedErrorId : ActiveDirectoryServer:8254,Microsoft.ActiveDirectory.Management.Commands.GetADUser

This answer is meant to help you troubleshoot your issue so we can understand what could be going wrong with your CSV.

Note, this code assumes that your CSV is comma delimited and the CSV has a column with name "UserPrincipalName".

$usersToAdd = foreach($line in Import-CSV "C:\Temp\jacktest.csv")
{
    if([string]::IsNullOrWhiteSpace($line.UserPrincipalName))
    {
        Write-Warning 'Empty UserPrincialName Value:'
        Write-Warning $line
        continue
    }

    $aduser = Get-ADUser -Filter "UserPrincipalName -eq '$($line.UserPrincipalName)'"
    if(-not $aduser)
    {
        Write-Warning "$($line.UserPrincipalName) could not be found."
        continue
    }

    $aduser
}

if($usersToAdd)
{
    Write-Host 'The following users will be added to the Group'
    $usersToAdd.UserPrincialName
    try
    {
        Add-ADGroupMember -Identity JackTest -Members $usersToAdd
    }
    catch
    {
        Write-Warning $_.Exception.Message
    }
}