Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PowerShell Active Directory – Can't use array value in filter for Get-ADUser

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

Both are Strings, both contain the exact same value.

When I run:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading