Syntax error when trying to filter users using Get-ADUser

Viewed 96

Good day,

Right now I'm writing a Powershell script to add users to a group from a CSV. The CSV contains the user's Name and only that. There's no second column or headers, the file is formatted like below:

JOHN.SMITH
JANE.DOE
FRED.EXAMPLE

I've written the following code to make the changes I want, but it throws a syntax error on Get-ADUser and I can't figure out why.

Import-Module ActiveDirectory
$UsersFile = Import-CSV "D:\Migrations\UsersForTestGroup.csv" -Header Name
Foreach($UserHeader in $UsersFile)
{
    $UserEntry = ($UserHeader -split '=',2 | select -last 1) -split '\ ',2 | select -first 1
    # This removes the header and trailing space and bracket that were there from the CSV import
    $User = Get-ADUser -Filter "Name -like $UserEntry"
    # This should then use that name to search for the correct $User but instead throws a syntax error
    Add-ADGroupMember -Identity "Test Group" -Members $User
}

Here's the error I get:

Get-ADUser : Error parsing query: 'Name -like JOHN.SMITH' Error Message: 'syntax error' at position: '12'.
At line:5 char:9
+ $User = Get-ADUser -Filter "Name -like $UserEntry"
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ParserError: (:) [Get-ADUser], ADFilterParsingException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Micr
   osoft.ActiveDirectory.Management.Commands.GetADUser

My guess is there's something causing the filter to not properly consider $UserEntry as a string, but I can't figure out how to fix that.

1 Answers

There are a couple issues with your example and question as the Get-Content cmdlet does not support the -Header parameter. I used this to test your example:

$UsersFile = Import-Csv "C:\Temp\test.csv" -Header Name
    Foreach($UserHeader in $UsersFile.Name){    # Note the change here to use $variable.Name
        # Line below is not needed as there are no "\" slashes
        # $UserEntry = ($UserHeader -split '=',2 | select -last 1) -split '\ ',2 | select -first 1
Write-Host $UserEntry}

I suspect the issue is with your example though as your error shows you have the JOHN.SMITH username correctly formatted. Assuming that is accurate, I believe the real issue is on the line:

$User = Get-ADUser -Filter "Name -like $UserEntry"

Which should look like this instead:

$User = Get-ADUser -Filter 'Name -like "$UserEntry"'
Related