Get-ADUser - the search filter cannot be recognized

q sligh 21 Reputation points
2023-10-31T13:35:29.7633333+00:00

The script below is what I'm attempting to use to solve three needs:

  1. From a csv add users by their "cn" attribute to multiple groups.
  2. If the user is not already in AD, create the user, using their "cn" attribute.
  • The CSV headers are as follows: CommonName, cn, groups
  • I can use "Get-ADUser -Filter "cn -eq 'cn'" and AD resolves to the name provided, but when I attempt to use that same command within the script, it states that it's not recognized.
  • Here's the script:
# Import the Active Directory module
Import-Module ActiveDirectory

# Define the CSV file path
$csvFilePath = "C:\Path\To\CSV\File.csv"

# Read the CSV file into a variable
$csvData = Import-Csv -Path $csvFilePath

# Iterate over each row in the CSV file
foreach ($row in $csvData) {

    # Get the user's CN
    $cn = $row["CommonName"]

    # Search for the user in Active Directory
    $user = Get-ADUser -Filter "CommonName -eq '$cn'"

    # If the user exists, add them to the specified groups
    if ($user -ne $null) {
        $groups = $row["Groups"].Split(",")
        foreach ($group in $groups) {
            Add-ADGroupMember -Identity $group -Members $user.SamAccountName
        }
    }
}

The result of my script is:

Get-ADUser : The search filter cannot be recognized
At D:\AddUser2Groups4.ps1:20 char:13
+     $user = Get-ADUser -Filter "CommonName -eq '$cn'"
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-ADUser], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:8254,Microsoft.ActiveDirectory.Management.Commands.GetADUser

I even changed "CommonName" to "cn" and the results are the same.

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 47,901 Reputation points
    2023-10-31T14:44:48.82+00:00

    Verify that the value you retrieve from the CSV column "CommonName" isn't a $null or zero-length string before you place its value into the $cn variable.

    You may have an empty row in your CSV, or an empty column.

    Also, using a CN to retrieve a user from the AD may result in your getting more than one user object. A CN is only guaranteed to be unique within an Organizational Unit, not a domain or a forest!


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.