Powershell – Get-ADUser in foreach loop returns nothing if using object

active-directorycsvpowershell

$users = Get-Content "C:\PowerShellScript\CSV\swyxusers.csv"


$test = Foreach ($user in $users){
Get-ADUser -Filter {Name -like "*$user*" } | Select-Object SamAccountName, Enabled
} 

$test| export-csv -Force -Append "C:\PowerShellScript\CSV\skit.csv"

Running above it results in nothing exported to the CSV, but if i add Write-Host "$User" it exports the list of users. So I know the exporting feature works.

If I run it like this:

$users = Get-Content "C:\PowerShellScript\CSV\swyxusers.csv"


$test = Foreach ($user in $users){
Get-ADUser -Filter {Name -like "*User 1*" } | Select-Object SamAccountName, Enabled
} 

$test| export-csv -Force -Append "C:\PowerShellScript\CSV\skit.csv"

It fills my CSV with the result of "User 1" (The first user in the document and this is the excepted result) for the amount of times there are rows in the $user variable. So I know my search method works.

So my question/issue is how to i get it to loop through my CSV file and actually find anything when searching using a object? Since it works when i use a manually entered string but not when using object.

The CSV is formated the following way:

USER 1
USER 2
USER 3
USER 4 

Edit:
Issue is not related to the foreach loop, If i run the following:

$test = "TEST USER"
Get-ADUser -Filter {Name -eq "*$test*"}

it still doesn't work, has to be something with how the filtering is done.

Best Answer

Typically when creating a search filter as a combination of multiple strings I avoid doing so in the input itself. So for example (and as you have found) instead of doing the following

Get-ADUser -Filter {Name -like "*$user*"}

I try to create a filter then call the function

$filter = "*" + $user + "*"
Get-ADUser -Filter {Name -like $filter}

I've found this to be the only way to successfully build an LDAP filter as a combination of multiple strings. This also enables you to verify your filter prior to running the query.