0

When I'm holding a variable and passing it to a commandlet I am getting inconsistent results. Maybe I am just plain using variables in powershell incorrectly? If there were a way to see exactly the line of code my Visual Studio Code was sending at runtime that would be helpful.

My code returns a $null object when executing those first two filters. I've confirmed that $username actually does contain the string "userLoginName" but it doesn't seem to pass to the Get-ADUser commandlet correctly.

PS C:\> $username = "userLoginName"

PS C:\> Get-ADUser -Filter {SAMAccountName -eq "$($username)"}
PS C:\> Get-ADUser -Filter {SAMAccountName -eq "$username"}
PS C:\> Get-ADUser -Filter {SAMAccountName -eq "userLoginName"}

Why is it that only the third -filter command runs successfully? The first two return $null, not a UserNotFound kind of exception or anything. What am I doing wrong here? Do I just have no concept of how to use variables in powershell (yes)? Sorry for being a noob, but thank you for your time.

1 Answers1

0

See this post. The AD calls' -Filter parameter doesn't like taking in string variables as part of a ScriptBlock for some reason (you can read the post more for more info). But passing -Filter as a String should work.

Get-ADUser -Filter "SAMAccountName -eq '$username'"

Alternatively, if you're just wanting to lookup an AD user with the SAMAccountName, you can just do Get-ADUser -Identity $username. That's probably easier. The benefit (or sometimes the consequence) of using the -Filter parameter is that, like you discovered, it won't throw an exception if a user is not found. If you use the -Identity parameter, it WILL throw an exception if a user is not found.

Nathan W
  • 283
  • 1
  • 6