Home > Net >  PowerShell Active Directory - Can't use array value in filter for Get-ADUser
PowerShell Active Directory - Can't use array value in filter for Get-ADUser

Time:06-03

I have two variables; $test and $accounts[0].upn

Both are Strings, both contain the exact same value.

When I run:

Get-ADUser -Filter "UserPrincipalName -eq '$test'"

I get the result I want, however when I run:

Get-ADUser -Filter "UserPrincipalName -eq '$accounts[0].upn'"

It does not return any result.

I get that $accounts is an array, but I thought I should get the same result given the variables are both of same type and value.

See my screenshot below a better understanding of what I am trying to achieve, I only made the $test variable for debugging and I would like the command to work with $accounts[0].upn. Apologies I had to black out some personal information for privacy reasons, it shouldn't hinder understanding the screenshot.

Demonstration Screenshot

Any help is much appreciated!

CodePudding user response:

The issue here is that powershell doesnt know when to stop interpreting the variable within the string (its called expression expansion).

so to fix this you should wrap any variable with properties in a sub expression so powershell knows when to stop expanding it.

Get-ADUser -Filter "UserPrincipalName -eq '$accounts[0].upn'"

Should become

Get-ADUser -Filter "UserPrincipalName -eq '$($accounts[0].upn)'"

Note the $() with your variable inside it.

  • Related